Spring---Bean的生命周期
Posted anpeiyong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring---Bean的生命周期相关的知识,希望对你有一定的参考价值。
1、概述
1.1、Spring对Bean的生命周期的操作提供了支持,提供2种方式:
1.1.1、java配置方式:
使用@Bean的initMethod,destoryMethod属性(相当于xml 配置文件中的init-method,destory-method);
1.1.2、注解方式:
使用JSR-250的@PostConstruct,@PreDestroy
需要使用JSR-250支持:
<!-- https://mvnrepository.com/artifact/javax.annotation/jsr250-api --> <dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifactId> <version>1.0</version> </dependency>
1.1.3、eg:
package com.an.config; import com.an.service.bean.BeanWayService; import com.an.service.bean.JSR250WayService; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * @description: * @author: anpeiyong * @date: Created in 2019/11/19 16:02 * @since: */ @Configuration @ComponentScan(value = "com.an") public class PrePostConfig { //第一种方式:java配置 @Bean(initMethod = "init",destroyMethod = "destroy") BeanWayService beanWayService(){ return new BeanWayService(); } //第二种方式:注解方式 @Bean JSR250WayService jsr250WayService(){ return new JSR250WayService(); } }
package com.an.service.bean; /** * @description: * @author: anpeiyong * @date: Created in 2019/11/19 16:04 * @since: */ public class BeanWayService { public BeanWayService(){ super(); System.out.println("初始化构造函数-BeanWayService"); } public void init(){ System.out.println("@Bean-init-method"); } public void destroy(){ System.out.println("@Bean-destroy-method"); } }
package com.an.service.bean; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; /** * @description: * @author: anpeiyong * @date: Created in 2019/11/19 16:07 * @since: */ public class JSR250WayService { public JSR250WayService(){ super(); System.out.println("初始化构造函数-JSR250WayService"); } //@PostConstruct在构造函数执行完后执行 @PostConstruct public void init(){ System.out.println("jsr250-init-method"); } //@PreDestroy在Bean销毁前执行 @PreDestroy public void destroy(){ System.out.println("jsr250-destroy-method"); } }
package com.an.main; import com.an.config.PrePostConfig; import com.an.service.bean.BeanWayService; import com.an.service.bean.JSR250WayService; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * @description: * @author: anpeiyong * @date: Created in 2019/11/19 16:14 * @since: */ public class BeanMainTest { public static void main(String[] args) { AnnotationConfigApplicationContext annotationConfigApplicationContext=new AnnotationConfigApplicationContext(PrePostConfig.class); BeanWayService beanWayService=annotationConfigApplicationContext.getBean(BeanWayService.class); JSR250WayService jsr250WayService=annotationConfigApplicationContext.getBean(JSR250WayService.class); annotationConfigApplicationContext.close(); } }
以上是关于Spring---Bean的生命周期的主要内容,如果未能解决你的问题,请参考以下文章