javascript
spring boot: Bean的初始化和销毁 (一般注入说明(三) AnnotationConfigApplicationContext容器 JSR250注解)...
?
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
使用AnnotationConfigApplicationContext可以實(shí)現(xiàn)基于Java的配置類加載Spring的應(yīng)用上下文.避免使用application.xml進(jìn)行配置。在使用spring框架進(jìn)行服務(wù)端開發(fā)時(shí),個(gè)人感覺注解配置在便捷性,和操作上都優(yōu)于是使用XML進(jìn)行配置;
?
使用JSR250注解需要在maven的pom.xml里面配置
<!-- 增加JSR250支持 --><dependency><groupId>javax.annotation</groupId><artifactId>jsr250-api</artifactId><version>1.0</version></dependency>
?
?
prepostconfig文件:
package ch2.prepost; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration;//聲明這是一個(gè)配置類 @Configuration //自動(dòng)掃描ch2.prepost包下的@Service,@Component,@Repository,@Contrller注冊(cè)為Bean @ComponentScan() public class PrePostConfig {//initMethod,destoryMethod制定BeanWayService類的init和destory在構(gòu)造方法之后、Bean銷毀之前執(zhí)行@Bean(initMethod="init",destroyMethod="destory")BeanWayService beanWayService(){return new BeanWayService();}//這是一個(gè)bean@BeanJSR250WayService jsr250WayService(){return new JSR250WayService();}}
JSR250WayService文件
package ch2.prepost; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy;public class JSR250WayService {//PostConstruct在構(gòu)造函數(shù)執(zhí)行完之后執(zhí)行@PostConstructpublic void init(){System.out.println("jsr250-init-method");}public JSR250WayService(){System.out.println("初始化構(gòu)造函數(shù)JSR250WayService");}//在Bean銷毀之前執(zhí)行@PreDestroypublic void destory(){System.out.println("jsr250-destory-method");}}
BeanWayService文件
package ch2.prepost;//使用@bean的形式bean public class BeanWayService {public void init(){ System.out.println("@Bean-init-method");}public BeanWayService(){super();System.out.println("初始化構(gòu)造函數(shù)-method");}public void destory(){ System.out.println("@Bean-destory-method");}}
運(yùn)行Main文件:
package ch2.prepost; import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {public static void main(String[] args){AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrePostConfig.class);BeanWayService beanWayConfig = context.getBean(BeanWayService.class);JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class);context.close();}}
?
運(yùn)行結(jié)果:
初始化構(gòu)造函數(shù)JSR250WayService
jsr250-init-method
jsr250-destory-method
初始化構(gòu)造函數(shù)-method
@Bean-init-method
@Bean-destory-method
?
總結(jié)
以上是生活随笔為你收集整理的spring boot: Bean的初始化和销毁 (一般注入说明(三) AnnotationConfigApplicationContext容器 JSR250注解)...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
 
                            
                        - 上一篇: wordpress中安装插件需要ftp服
- 下一篇: 前端程序员的一些有学习借鉴作用的网站
