Spring Bean在使用之前或使用之后需要做一些操作,Spring对Bean
的生命周期的操作提供了支持。
配置
- Java配置方式
使用@Bean
的initMethod
和destroyMethod
。相当于XML配置的init-method
和destory-method
。 - 注解方式
利用JSR-250
的@PostConstruct
和@PreDestroy
。
@PostConstruct:在构造函数执行完后执行。
@PreDestroy:在Bean销毁之前执行。
示例
- 导包
js4250-api.jar
使用
@Bean
形式的Beanpackage com.bean.initAndDestroy; /** * 使用@Bean形式的Bean * @author Rocky * */ public class BeanWayService { public void init() { System.out.println("@Bean-init-method"); } public BeanWayService() { super(); System.out.println("初始化构造函数-BeanWayService"); } public void destroy() { System.out.println("@Bean-destroy-method"); } }
使用
JSR250
形式的Beanpackage com.bean.initAndDestroy; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; /** * 使用JSR250形式的Bean * @author Rocky * */ public class JSR250WayService { @PostConstruct public void init() { System.out.println("jsr250-init-method"); } public JSR250WayService() { super(); System.out.println("初始化构造函数-JSR250WayService"); } @PreDestroy public void destory() { System.out.println("jsr250-destroy-method"); } }
配置类
package com.bean.initAndDestroy; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.bean.initAndDestroy") public class PrePostConfig { @Bean(initMethod="init", destroyMethod="destroy") BeanWayService beanWayService() { return new BeanWayService(); } @Bean JSR250WayService jsr250WayService() { return new JSR250WayService(); } }
执行Main类
package com.bean.initAndDestroy; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MainPrePost { @SuppressWarnings("unused") public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrePostConfig.class); BeanWayService beanWayService = context.getBean(BeanWayService.class); JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class); context.close(); } }
结果
初始化构造函数-BeanWayService @Bean-init-method 初始化构造函数-JSR250WayService jsr250-init-method jsr250-destroy-method @Bean-destroy-method
更多内容请访问:IT源点
注意:本文归作者所有,未经作者允许,不得转载