日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

spring boot: Bean的初始化和销毁 (一般注入说明(三) AnnotationConfigApplicationContext容器 JSR250注解)...

發布時間:2025/3/21 javascript 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 spring boot: Bean的初始化和销毁 (一般注入说明(三) AnnotationConfigApplicationContext容器 JSR250注解)... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

使用AnnotationConfigApplicationContext可以實現基于Java的配置類加載Spring的應用上下文.避免使用application.xml進行配置。在使用spring框架進行服務端開發時,個人感覺注解配置在便捷性,和操作上都優于是使用XML進行配置;

?

使用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;//聲明這是一個配置類 @Configuration //自動掃描ch2.prepost包下的@Service,@Component,@Repository,@Contrller注冊為Bean @ComponentScan() public class PrePostConfig {//initMethod,destoryMethod制定BeanWayService類的init和destory在構造方法之后、Bean銷毀之前執行@Bean(initMethod="init",destroyMethod="destory")BeanWayService beanWayService(){return new BeanWayService();}//這是一個bean@BeanJSR250WayService jsr250WayService(){return new JSR250WayService();}}

  

JSR250WayService文件

package ch2.prepost; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy;public class JSR250WayService {//PostConstruct在構造函數執行完之后執行@PostConstructpublic void init(){System.out.println("jsr250-init-method");}public JSR250WayService(){System.out.println("初始化構造函數JSR250WayService");}//在Bean銷毀之前執行@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("初始化構造函數-method");}public void destory(){ System.out.println("@Bean-destory-method");}}

  

運行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();}}

  

?

運行結果:

初始化構造函數JSR250WayService
jsr250-init-method

jsr250-destory-method


初始化構造函數-method

@Bean-init-method

@Bean-destory-method

?

總結

以上是生活随笔為你收集整理的spring boot: Bean的初始化和销毁 (一般注入说明(三) AnnotationConfigApplicationContext容器 JSR250注解)...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。