package com.example.demo_2_3;
/**
* Created by WangBin on 2017/4/12.
*
*/
public class BeanWayService {
public void init(){
System.err.println("BeanWayService 的初始化方法");
}
public BeanWayService(){
super();
System.err.println("BeanWayService 的 构造方法");
}
public void destroy(){
System.err.println("BeanWayService 的销毁方法");
}
}
package com.example.demo_2_3;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* Created by WangBin on 2017/4/12.
*
*/
public class JSR250WayService {
@PostConstruct //在构造函数执行完成之后执行
public void init(){
System.err.println("JSR250WayService的 初始化方法");
}
public JSR250WayService(){
super();
System.err.println("JSR250WayService 的 构造方法");
}
@PreDestroy// 在 bean销毁之前执行
public void destroy(){
System.err.println("JSR250WayService 的销毁方法");
}
}
package com.example.demo_2_3;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Created by WangBin on 2017/4/12.
*
*/
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();
}
}
package com.example.demo_2_3;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Created by WangBin on 2017/4/12.
*
*/
@Configuration
@ComponentScan("com.example.demo_2_3")
public class PrePostConfig {
@Bean(initMethod = "init",destroyMethod = "destroy")// = 里写的是在 BeanWayService 里写的方法
BeanWayService beanWayService(){
return new BeanWayService();
}
@Bean//指定 JSR250WayService是一个bean
JSR250WayService jsr250WayService(){
return new JSR250WayService();
}
}
//先运行 构造方法 再运行 初始化方法 最后 执行销毁方法在bean销毁之前
//JSR250 销毁比较快 编写方式比较简单