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