文章目录
IOC即控制反转,传统的方式是自己直接控制对象,这种方式可称为“正转”;由IOC容器代为管理对象则称为“反转”。(自己做饭 —> 餐厅点餐)
1. 实现(简单工厂模式、工厂方法模式)
- BeanFactory 是Spring基础接口
- ApplicationContext(Spring上下文) 是 BeanFactory 接口 的扩展
<?xml version="1.0" encoding="UTF-8"?> <beans 命名空间> <bean id="id" class="全类名"> <property name="属性名1" value="属性值1"/> .... </bean> .... </beans>
2. Bean定义
属性 | 描述 |
---|---|
class | 指定Bean类名,必选 |
name | 指定Bean唯一标识 |
scope | 作用域(singleton、prototype、request、session、global-session) |
<constructor-arg ref=""/> | 基于构造函数依赖注入 |
<properties name="" ref=""/> | 基于setter依赖注入 |
autowiring | 自动装配 |
lazy-initialization | 延迟加载 |
init-method | 创建完毕回调 |
destroy-method | 销毁回调 |
3. 作用域
singleton:单例模式;
prototype:原型模式 ,多例;
request :每次HTTP请求创建新Bean,仅适用于WebApplicationContext 环境;
session:仅同一HTTP Session共享Bean,仅适用于WebApplicationContext 环境;
global-session: Portlet 应用环境,仅适用于WebApplicationContext 环境。
☆Portlet :web组件。
4. 生命周期(创建、销毁)
- 创建: 实现InitializingBean 接口 afterPropertiesSet() 方法;
- 销毁: 实现 DisposableBean 接口 destroy() 方法;
- XML方式使用 init-method、destroy-method属性指定回调方法。
5. 注入集合
四种类型: list 、set、map、props(key-value类型均为String)
<property name="list">
<list>
<ref bean="bean"/>
<value>value</value>
</list>
</property>
<property name="set">
<set>
<ref bean="bean"/>
<value>value</value>
</set>
</property>
<property name="map">
<map>
<entry key="key1" value="value"/>
<entry key ="key2" value-ref="ref"/>
</map>
</property>
6. 自动装配
- byNmae:通过参数名自动装配,容器自动匹配并装配和该Bean的属性具有相同名字的Bean;
- byType:通过参数类型自动装配,容器自动匹配并装配和该Bean的属性具有相同类型的Bean,若匹配失败,则抛出异常;
- constructor:类似byType,通过有参构造器自动装配,若匹配失败,则抛出异常。
7. 注解
- @Required:用于Bean的setter方法,受影响的属性必须XML文件中配置,否则抛出 BeanInitializationException 异常;
- @Autowired:自动连接Bean,可用于属性、setter和构造器;
- @Qualifier:多个相同类型Bean根据 id 选择其一注入,结合@Autowired使用。
8. JSR-250注解
- @PostConstruct 和 @PreDestroy:分别对应init-method 和 destroy-method;
- @Resource: @Autowired 和 @Qualifier 组合效果。
9. 基于java的配置
@Configuration:用于定义配置类,等价<beans></beans>;
@Bean:等价<bean><beans/>,默认方法名为id,返回值注入到 IOC 容器中;
@Import:从另一个配置类中加载Bean。
10. 监听上下文事件
实现 ApplicationListener<T> 接口的 onApplicationEvent方法
- ContextRefreshedEvent : ApplicationContext 初始化或刷新时;
- ContextStartedEvent : 使用start() 方法时;
- ContextStoppedEvent :使用 stop() 方法时;
- ContextClosedEvent:使用 close () 方法时;
- RequestHandledEvent : 告诉所有Bean HTTP请求已经被服务。
11. 自定义事件
- 定义:继承ApplicationEvent并使用其构造器;
- 发布:实现ApplicationEventPublisherAware接口,通过ApplicationEventPublisher对象发布事件;
- 监听:实现ApplicationListener接口,onApplicationEvent方法处理,或使用**@EventListener**定义监听方法;
- 注册监听器到IOC容器。