上文 介绍了控制反转的思想,并且提到在Spring中有一个专门的容器负责创建和管理bean,并将对象依赖的其它对象注入到这个容器中,这个容器我们一般称为IoC Container(IOC容器)。Spring有两个接口实现IOC容器,分别是BeanFactory接口和ApplicationContext接口,其中ApplicationContext接口继承BeanFactory,是它的超集。在BeanFactory的基础上ApplicationContext增加了:
-
更容易与Spring的AOP集成的特性
-
消息处理机制(用于国际化)
-
事件发布
-
应用程序层的上下文,如用于web应用程序的WebApplicationContext。
在pom.xml中添加依赖,目前最新的spring版本是5.3.20,我们使用最新版
org.springframework spring-beans 5.3.20 org.springframework spring-core 5.3.20 org.springframework spring-context 5.3.20 org.springframework spring-expression 5.3.20
之前的dao层和service层的代码不变,添加两个xml配置文件
daos.xml
service.xml
关键就是这个标签,其中id是我们为这个bean指定的唯一标识,class是这个类的全路径。bean标签其它的一些属性可以参考:
http://www.javashuo.com/article/p-tlyzqkrl-nc.html
最终程序结构变成这样
接下来修改测试类,ClassPathXmlApplicationContext继承了AbstractXmlApplicationContext,实现了ApplicationContext接口。现在由于IOC容器为我们管理和初始化对象了,我们不再需要主动去new,代码如下:
import com.hrx.dao.UserDaoImpl;
import com.hrx.service.UserService;
import com.hrx.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("daos.xml","service.xml");
UserService userService = context.getBean("userDaoServiceImpl", UserServiceImpl.class);
userService.setUserDao(context.getBean("userDaoImpl", UserDaoImpl.class));
userService.getUserName();
}
}
测试一下:



