IoC是一个概念,是一种思想,不是实现,实现方式有多种。比较流行的方式有2种:
依赖查找(DL Dependency Lookup)、依赖注入(DI Dependency Injection)。
依赖注入方式应用更加广泛,Spring就是采用的DI方式。
1、创建Service接口
public interface ISomeService {
void doSome();
}
2、实现Service接口
public class SomeServiceImpl implements ISomeService {
//无参构造函数
public SomeServiceImpl() {
System.out.println("执行无参构造函数");
}
@Override
public void doSome() {
System.out.println("执行doSome()方法");
}
}
3、创建applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 注册 Service
相当于 SomeServiceImpl myService = new SomeServiceImpl(); -->
<bean id="myService" class="com.xxx.spring.service.SomeServiceImpl"/>
</beans>
4、测试代码
public class MyTest {
//传统方式
@Test
public void test1() {
ISomeService service = new SomeServiceImpl();
service.doSome();
}
// spring方式-1
// 代码中完全没有出现SomeServiceImpl实现类,只知道接口。实现解耦。
// 以后就算怎么修改SomeServiceImpl实现类,代码都不用动。就算修改类名,只需修改配置
@Test
public void test2() {
//创建容器对象,加载spring配置文件
//类根目录路径找配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
ISomeService service = (ISomeService) ac.getBean("myService");
service.doSome();
}
//spring方式-2
@Test
public void test3() {
// 创建容器对象,加载spring配置文件
// 默认:项目根目录下面找
// 3-01-spring/applicationContext_file.xml
// 其实可以放在系统的任意位置 比如D:盘等等
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext_file.xml");
ISomeService service = (ISomeService) ac.getBean("myService");
service.doSome();
}
//spring方式=3
// ApplicationContext容器和BeanFactory容器的不同【通过debug可以看出】
// ApplicationContext是接口,继承了BeanFactory。BeanFactory是根接口
// 这2个容器对于其中Bean的创建时机不同:
// 1)ApplicationContext容器在进行初始化时,会将其中所有的Bean(对象)进行创建
// 缺点:占用系统资源(CPU、内存)
// 优点:响应速度快
// 2)BeanFactory容器中的对象,在容器初始化时并不会创建,而是在真正获取该对象时才被创建
// 缺点:相对来说,响应速度慢
// 优点:不多占用系统资源
@Test
public void test4() {
BeanFactory ac = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
ISomeService service = (ISomeService) ac.getBean("myService");
service.doSome();
}
}