配置文件
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">注解驱动
@Bean(initMethod = "init", destroyMethod = "close") @ConfigurationProperties(prefix = "spring.datasource") public DataSource getDataSources() { return new DruidDataSource(); }
Bean 实现 InitializingBean、 DisposableBean。
Bean 方法使用 @PostConstruct 和 @PreDestroy 修饰
Bean 的声明周期可以理解为:创建 > 初始化 > 销毁
创建:单实例(容器启动时创建)、多实例(每次获取时创建)
初始化:对象创建完成,并赋值好,调用初始化方法
销毁:单实例(容器关闭的时候)、多实例(容器不管理,需要手动调用)
在使用 xml 配置 bean 时,使用的是 init-method 和 destroy-method 指定初始化和销毁方法:
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">init-method 属性说明:
The name of the custom initialization method to invoke after setting bean properties. The method must have no arguments, but may throw any exception. This is an alternative to implementing Spring's InitializingBean interface or marking a method with the PostConstruct annotation.
方法必须无参,但可以抛出异常,也可以实现 Spring 的接口 InitializeingBean 或者在方法上加入 @PostConstruct 注解。
destroy-method 属性说明:
The name of the custom destroy method to invoke on bean factory shutdown. The method must have no arguments, but may throw any exception. This is an alternative to implementing Spring's DisposableBean interface or the standard Java Closeable/AutoCloseable interface, or marking a method with the PreDestroy annotation. Note: Only invoked on beans whose lifecycle is under the full control of the factory - which is always the case for singletons, but not guaranteed for any other scope.
方法必须无参,但可以抛出异常,也可以用 Spring 的 DisposableBean 接口或者标准 Java 接口 Closeable / AutoCloseable;或者在方法上加入 @PreDestroy 注解
也可以使用 JavaConfig 方式注入
@Bean(initMethod = "init", destroyMethod = "close") @ConfigurationProperties(prefix = "spring.datasource") public DataSource getDataSources() { return new DruidDataSource(); }这两种方式可以保持 Bean 的纯净。
通过 Bean 实现 InitializingBean 和 DisposableBean。
该接口常常用于创建完毕之后初始化使用
SqlSessionFactoryBean 实现了 InitializingBean,并实现了 afterPropertiesSet() 方法,用于构建 SqlSessionFactory。
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent>
销毁 Bean 时调用的方法
SqlSessionTemplate 实现了 DisposableBean
public class SqlSessionTemplate implements SqlSession, DisposableBean
JSR-250 @PostConstruct 和 @PreDestory 注解通常被认为是 Spring 应用生命周期回调的最佳实践。使用这两个注解意味着你的 Bean 不会与 Spring 特征接口耦合。
