IOC: 控制反转
将类的创建权力反转给spring框架,由spring框架来创建类对象,方便解耦。
IOC模块需要引入的jar包
Beans :Bean工厂及Bean装配
Core :IOC及DI 的基本实现
Context :Spring上下文即IOC容器
Expression Language :SPEL Spring表达式语言
还需要引入Spring依赖的日志包
c
om.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.apache.log4j-1.2.15.jar -----(实现)
要将项目中的类的创建权反转给Spring,需要创建Spring的配置文件,配置文件可以是任意名称,但建议使用默认名称:ApplicationContent.xml便于维护。
编写配置文件需要先引入约束,Spring官方给的约束头信息在
spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\html\xsd-config.html 文件中;
具体约束如下:
<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">
</beans>
配置Bean管理
//
将
Service
的创建交给
spring
<bean id="userService" class="com.spring.demo1.UserServiceImpl"/>
获取Bean
public void demo2(){
//
使用
Spring
的工厂
:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//
通过工厂获得类
:
UserService userService = (UserService) applicationContext.getBean("userService");
userService.sayHello();
}
Spring框架中的工厂
1. ApplicationContext
接口
*
使用
ApplicationContext
工厂的接口,使用该接口可以获取到具体的
Bean
对象
*
该接口下有两个具体的实现类
* ClassPathXmlApplicationContext --
加载类路径下的
Spring
配置文件
* FileSystemXmlApplicationContext --
加载本地磁盘下的
Spring
配置文件
2. BeanFactory
工厂(是
Spring
框架早期的创建
Bean
对象的工厂接口)(了解)
1.
使用
BeanFactory
接口也可以获取到
Bean
对象
*
代码如下:
public void run(){
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
UserService us = (UserService) factory.getBean("us");
us.sayHello();
}
2. BeanFactory
和
ApplicationContext
的区别
* BeanFactory -- BeanFactory
采取延迟加载,第一次
getBean
时才会初始化
Bean
* ApplicationContext --
在加载
applicationContext.xml
时候就会创建具体的
Bean
对象的实例,还提供了一些其他的功能
*
国际化处理
*
事件传递
* Bean
自动装配
*
各种不同应用层的
Context
实现