参考二里面的明细3
public class TestCase {
AnnotationConfigApplicationContext ctx;
@Before
public void init(){
ctx = new AnnotationConfigApplicationContext(Config.class);
System.out.println("初始化Spring");
}
@After
public void destroy(){
ctx.close();
System.out.println("销毁Spring");
}
@Test
public void testScope(){
Date d= ctx.getBean("myDate", Date.class);
System.out.println(d);
}
}
生命周期管理是否需要使用,根据具体业务需求而定;
注意:因为以下注解不属于Spring,属于annotation,所以要单独引入
创建对象以后自动执行
关闭容器关闭对象时候执行
组件代码:
@Component
public class FileLogger03 {
public PrintWriter out;
@PostConstruct
//Spring创建Bean对象后自动执行初始化方法
public void open() throws Exception{
out =new PrintWriter("Demo.text");
System.out.println("打开Demo.text");
}
@PreDestroy
//Spring 容器关闭时销毁对象,自动执行销毁方法
public void close() {
out.close();
System.out.println("关闭Demo.text");
}
}
配置类代码:
@Configuration
@ComponentScan(basePackages = "cn.tedu.demo")
public class Config {
}
测试类代码:
public class TestCase {
AnnotationConfigApplicationContext ctx;
@Before
public void init(){
ctx = new AnnotationConfigApplicationContext(Config.class);
}
@After
public void destroy(){
ctx.close();
}
@Test
public void testScope(){
FileLogger03 ff= ctx.getBean("fileLogger03",FileLogger03.class);
ff.out.println("aaaaaaa");
ff.out.println("ddddddd");
System.out.println("life test");
}
}
组件代码:
//配置类采用了@Bean ,所以此处不用再@Component
public class DemoLogger {
public PrintWriter out;
public void open() throws Exception{
out =new PrintWriter("Demo.text");
System.out.println("打开Demo.text");
}
public void close() {
out.close();
System.out.println("关闭Demo.text");
}
}
配置类:
@Configuration
//因为是采用@Bean标注,所以@ComponentScan可以省略
public class Config {
@Bean(initMethod = "open",destroyMethod = "close")
public DemoLogger demoLogger(){
return new DemoLogger();
}
}
测试类:
@Test
public void testLogger(){
DemoLogger gl = ctx.getBean("demoLogger", DemoLogger.class);
gl.out.println("good morning!");
}
每次都创建一个对象,Spring为了避免内存泄漏,不会缓存对象的引用,所以Spring关闭时候就无法处理对象的销毁方法,需要手动销毁.
配置类:
@Bean(initMethod = "open",destroyMethod = "close")
@Scope("prototype")
public DemoLogger demoLogger(){
return new DemoLogger();
}
测试类:
@Test
public void testLogger(){
DemoLogger gl = ctx.getBean("demoLogger", DemoLogger.class);
gl.out.println("good morning!");
gl.close(); //因为开启了 @Scope("prototype"),此处需要手动关闭
}
前提组件有@Component,会自动创建;不想创建的话就是加上@Lazy
@Component
@Lazy
public class FileLogger03 {
public PrintWriter out;
@PostConstruct
//Spring创建Bean对象后自动执行初始化方法
public void open() throws Exception{
out =new PrintWriter("Demo.text");
System.out.println("111打开Demo.text");
}
@PreDestroy
//Spring 容器关闭时销毁对象,自动执行销毁方法
public void close() {
out.close();
System.out.println("111关闭Demo.text");
}
}
配置中
@Bean
@Lazy
public DemoLogger demoLogger(){
return new DemoLogger();
}
@Configuration
@ComponentScan(basePackages = "cn.tedu.demo")
@Import({SysConfig.class})
public class Config {
}