package com.wisely.highlight_spring4.ch2.prepost;
public class BeanWayService {
public void init(){
System.out.println("@Bean-init-method");
}
public BeanWayService() {
super();
System.out.println("初始化构造函数-BeanWayService");
}
public void destroy(){
System.out.println("@Bean-destory-method");
}
}
(3)使用JSR250形式的Bean。
package com.wisely.highlight_spring4.ch2.prepost;
public class JSR250WayService {
@PostConstruct //1 在构造函数执行完之后执行
public void init(){
System.out.println("jsr250-init-method");
}
public JSR250WayService() {
super();
System.out.println("初始化构造函数-JSR250WayService");
}
@PreDestroy //2 在Bean销毁之前执行
public void destroy(){
System.out.println("jsr250-destory-method");
}
}
(4)配置类。
package com.wisely.highlight_spring4.ch2.prepost;
@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.prepost")
public class PrePostConfig {
@Bean(initMethod="init",destroyMethod="destroy") //1 指定BeanWayService类的init和destroy方法在构造之后、Bean销毁之前执行
BeanWayService beanWayService(){
return new BeanWayService();
}
@Bean
JSR250WayService jsr250WayService(){
return new JSR250WayService();
}
}
(5)运行。
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(PrePostConfig.class);
BeanWayService beanWayService = context.getBean(BeanWayService.class);
JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class);
context.close();
}
}