实际开发的过程中经常遇到Bean在使用之前或者之后做些必要的操作
Spring对Bean的生命周期的操作提供了支持。在使用java配置和注解配置下提供如下两种方式
1.java配置方式:使用@Bean的initMethod和destroyMethod(相当于xml配置的init-method和destory-method)
2.注解方式:利用JSR-250的@PostConstruct和@PreDestroy
增加支出JSR250
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
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-destory-method");
}
}
public class JSR250WayService {
@PostConstruct
public void init(){
System.out.println("4...jsr250-init-method");
}
public JSR250WayService(){
super();
System.out.println("5...初始化构造函数-JSR250WayService");
}
@PreDestroy
public void destroy(){
System.out.println("6...jsr250-destory-method");
}
}
@Configuration
@ComponentScan("com.example.demo.prepost")
public class PrePostConfig {
/**
* initMethod和destroyMethod指定
* Bean WayService类
* init 和 destroy方法在构造之后
* Bean销毁之前执行
* @return
*/
@Bean(initMethod="init",destroyMethod="destroy")
BeanWayService beanWayService(){
return new BeanWayService();
}
@Bean
JSR250WayService jsr250WayService(){
return new JSR250WayService();
}
}
@SpringBootApplication
public class DemoApplication {
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();
}
}