Spring Bean在使用之前或使用之后需要做一些操作,Spring对Bean
的生命周期的操作提供了支持。
配置
- Java配置方式
使用@Bean
的initMethod
和destroyMethod
。相当于XML配置的init-method
和destory-method
。
- 注解方式
利用JSR-250
的@PostConstruct
和@PreDestroy
。
**@PostConstruct:**在构造函数执行完后执行。
@PreDestroy:在Bean销毁之前执行。
示例
- 导包
js4250-api.jar
- 使用
@Bean
形式的Bean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package com.bean.initAndDestroy;
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
形式的Bean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| package com.bean.initAndDestroy;
import javax.annotation.PostConstruct; import javax.annotation.PreDestroy;
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"); } }
|
- 配置类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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(); } }
|
- 结果
1 2 3 4 5 6
| 初始化构造函数-BeanWayService @Bean-init-method 初始化构造函数-JSR250WayService jsr250-init-method jsr250-destroy-method @Bean-destroy-method
|