Spring 对Bean的生命周期的操作提供了支持。具体实现又两种方式
1.使用@Bean 中的 initMethod 和 destroyMethod
2.注解方式 利用JSR-250 中的@PostConstruct 和 @PreDesctroy
两种方式的具体用法如下
1.创建功能,为了快速完成项目构建,我们使用 https://start.spring.io/ 网址来快速生成项目
2.引入Jsr250 支持
<dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifactId> <version>1.0</version> </dependency>
3.使用@Bean 的形式
package com.lvlvstart.example.service; public class BeanWayService { public void init(){ System.out.println("@Bean-init-method - BeanWayService"); } public BeanWayService(){ super(); System.out.println("Init constructor method - BeanWayService"); } public void destroy(){ System.out.println("@Bean-destory-method - BeanWayService"); } }
4.使用Jsr250的形式
package com.lvlvstart.example.service; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; public class Jsr250Service { @PostConstruct public void init(){ System.out.println("@Bean-init-method-Jsr250Service"); } public Jsr250Service(){ super(); System.out.println("Init constructor method - Jsr250Service"); } @PreDestroy public void destroy(){ System.out.println("@Bean-destory-method-Jsr250Service"); } }
5.配置类
package com.lvlvstart.example.config; import com.lvlvstart.example.service.BeanWayService; import com.lvlvstart.example.service.Jsr250Service; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.lvlvstart.example") public class Config { @Bean(initMethod = "init" , destroyMethod = "destroy") BeanWayService beanWayService(){ return new BeanWayService(); } @Bean Jsr250Service jsr250Service(){ return new Jsr250Service(); } }
6.启动类
package com.lvlvstart.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ExampleApplication { public static void main(String[] args) { SpringApplication.run(ExampleApplication.class, args); } }
参考资料: 《Spring Boot 实战 》 王云飞 著