1.IoC是什么
Ioc(Inversion of Control),为控制反转也称依赖注入(DI—Dependency Injection),他不是技术,而是一种思想,即把设计好的对象交给Ioc容器控制,而不是由我们在程序的内部控制。为什么要这么做?Ioc可以降低程序的耦合。而在思想的改变为,以前应用程序是老大,我要什么资源外部就给什么资源,但是现在有了Ioc,程序依赖外部给我资源。应用程序从主动变成了被动。
2.Spring中的Ioc容器
在Spring中,通过读取配置文件生成BeanDefinition,IoC容器根据BeanDefinition进行实例化,把我们设计好的对象交给Ioc容器管理,而Ioc容器管理的这些对象我们称之为Bean。他由Spring的Ioc容器初始化,装配,和管理。
3.实际举例
package com.douhao.service;
public interface StudentService {
public void learn();
}
package com.douhao.serviceImpl;
import com.douhao.service.StudentService;
public class StudentServiceImpl implements StudentService {
@Override
public void learn() {
System.out.println("正在学习。。。");
}
}
package com.douhao.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.douhao.service.StudentService;
public class SpringTest {
public static void main(String[] args) {
//1、读取配置文件实例化一个IoC容器
ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext.xml");
//2、从容器中获取Bean,注意此处完全“面向接口编程,而不是面向实现”
StudentService sts=(StudentService)context.getBean("studentService");
//3、执行业务逻辑
sts.learn();
}
}
4.详解IoC容器
在Spring Ioc容器的代表就是org.springframework.beans包中的BeanFactory接口,BeanFactory接口提供了IoC容器最基本功能;而org.springframework.context包下的ApplicationContext接口扩展了BeanFactory,还提供了与Spring AOP集成、国际化处理、事件传播及提供不同层次的context实现 (如针对web应用的WebApplicationContext)。简单说, BeanFactory提供了IoC容器最基本功能,而 ApplicationContext 则增加了更多支持企业级功能支持。ApplicationContext完全继承BeanFactory,因而BeanFactory所具有的语义也适用于ApplicationContext。
Spring容器一览:
1.XmlBeanFactory:BeanFactory实现,提供基本的IoC容器功能,可以从classpath或文件系统等获取资源;
(1) File file = new File("fileSystemConfig.xml");
Resource resource = new FileSystemResource(file);
BeanFactory beanFactory = new XmlBeanFactory(resource);
(2)
Resource resource = new ClassPathResource("classpath.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);
2.ClassPathXmlApplicationContext:ApplicationContext实现,从classpath获取配置文件;
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath.xml");
3.FileSystemXmlApplicationContext:ApplicationContext实现,从文件系统获取配置文件。
BeanFactory beanFactory = new FileSystemXmlApplicationContext("fileSystemConfig.xml");