前文已经描述了Bean的作用域,本文将描述Bean的一些生命周期作用,配置还有Bean的继承。
定制Bean
生命周期回调
开发者通过实现Spring的InitializeingBean
和DisposableBean
接口,就可以让容器来管理Bean的生命周期。容器会调用afterPropertiesSet()
前和destroy()
后才会允许Bean在初始化和销毁Bean的时候执行一些操作。
JSR-250的
@PostConstruct
和@PreDestroy
注解就是现代Spring应用生命周期回调的最佳实践。使用这些注解意味着Bean不在耦合在Spring特定的接口上。详细内容,后续将会介绍。
如果开发者不想使用JSR-250的注解,仍然可以考虑使用init-method
和destroy-method
定义来解耦。
内部来说,Spring框架使用BeanPostProcessor
的实现来处理任何接口的回调,BeanPostProcessor
能够找到并调用合适的方法。如果开发者需要一些Spring并不直接提供的生命周期行为,开发者可以自行实现一个BeanPostProcessor
。更多的信息可以参考后面的容器扩展点。
除了初始化和销毁回调,Spring管理的对象也实现了Lifecycle
接口来让管理的对象在容器的生命周期内启动和关闭。
生命周期回调在本节会进行详细描述。
初始化回调
org.springframework.beans.factory.InitializingBean
接口允许Bean在所有的必要的依赖配置配置完成后来执行初始化Bean的操作。InitializingBean
接口中特指了一个方法:
void afterPropertiesSet() throws Exception;
Spring团队建议开发者不要使用InitializingBean
接口,因为这样会不必要的将代码耦合到Spring之上。而通过使用@PostConstruct
注解或者指定一个POJO的实现方法,比实现接口要更好。在基于XML的配置元数据上,开发者可以使用init-method
属性来指定一个没有参数的方法。使用Java配置的开发者可以使用@Bean
之中的initMethod
属性,比如如下:
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {
public void init() {
// do some initialization work
}
}
与如下代码一样效果:
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}
但是前一个版本的代码是没有耦合到Spring的。
销毁回调
实现了org.springframework.beans.factory.DisposableBean
接口的Bean就能通让容器通过回调来销毁Bean所用的资源。DisposableBean
接口包含了一个方法:
void destroy() throws Exception;
同InitializingBean同样,Spring团队仍然不建议开发者来使用DisposableBean
回调接口,因为这样会将开发者的代码耦合到Spring代码上。换种方式,比如使用@PreDestroy
注解或者指定一个Bean支持的配置方法,比如在基于XML的配置元数据中,开发者可以在Bean标签上指定destroy-method
属性。而在Java配置中,开发者可以配置@Bean
的destroyMethod
。
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
public class ExampleBean {
public void cleanup() {
// do some destruction work (like releasing pooled connections)
}
}
上面的代码配置和如下配置是等同的:
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements