文章目录
IoC控制反转
使用对象时,由主动new产生对象转换为由外部提供对象,对象创建控制权由程序转移到外部。
一开始是这样的:
后来变成了:
dao对象不用自己new
使用对象时不仅可以直接从IoC容器中获取,并且获取到的bean已经绑定了所有的依赖关系。
Demo Spring开发步骤(入门)
1.导入spring的坐标spring-context(pom.xml)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
2.配置bean(applicationContext.xml)
原本我们是这样配的
<!--配置bean-->
<!--bean标签表示配置bean
id属性表示给bean起名字
class属性表示给bean定义类型-->
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl"/>
<bean id="bookService" class="com.com.itheima.service.impl.BookServiceImpl"/>
对应的业务层实现
private BookDao bookDao = new BookDaoImpl();
现在service层实现类BookServiceImpl已经与之前不同了,如下:
package com.itheima.service.impl;
import com.itheima.dao.BookDao;
import com.itheima.service.BookService;
public class BookServiceImpl implements BookService {
//private BookDao bookDao = new BookDaoImpl();
//删除业务层中使用new的方式创建的dao对象
//Service中需要的Dao对象如何进入到Service中?生成一个set方法,由IoC容器执行
private BookDao bookDao;
public void save() {
System.out.println("book service save .....");
bookDao.save();
}
//提供对应的set方法
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
}
注意:
1.Dao对象由IoC容器创建
2.生成一个setter方法,把Dao对象给Service
那么问题来了,Service与Dao之间的关系如何描述?Spring如何知道?
通过配置。
需要将原来的bean配置稍作修改
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl"/>
<!--<bean id="bookService" class="com.com.itheima.service.impl.BookServiceImpl"/>-->
<bean id="bookService" class="com.itheima.service.impl.BookServiceImpl" scope="prototype">
<!--配置service与dao的关系-->
<!--property标签表示配置当前bean的属性
name属性表示配置哪一个具体属性(BookServiceImpl.java)属性的名称
ref属性表示参照哪一个bean(applicationContext.xml) 容器中对应的bean的名称-->
<property name="bookDao" ref="bookDao"/>
</bean>
3.拿IoC容器,拿bean,运行程序(App2.java)
package com.itheima;
import com.itheima.dao.BookDao;
import com.itheima.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App2 {
public static void main(String[] args) {
//想拿bean,得先拿IoC容器,加载配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取bean
// BookDao bookDao = (BookDao) ctx.getBean("bookDao");
// bookDao.save();
BookService bookService = (BookService) ctx.getBean("bookService");
//BookService bookService = (BookService) ctx.getBean(BookService.class);
bookService.save();
}
}