之前的版本中 bean 是可以在xml文件中 配置bean的初始化和销毁的method
<bean id = "person" class="com.enjoy.cap1.Person" init-method="" destroy-method="">
<property name="name" value="wyl"></property>
<property name="age" value="19"></property>
</bean>
接下来自己模拟一个创建–》 初始化 --》销毁的流程
package com.enjoy.cap7;
public class Bike {
public Bike(){
System.out.println("Bike constructor ………………");
}
public void init(){
System.out.println("Bike init ……………………");
}
public void destory(){
System.out.println("Bike destory…………………");
}
}
package com.enjoy.cap7;
import com.enjoy.cap1.Person;
import com.enjoy.cap6.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(value = {Dog.class,Cat.class,TTTTImportSelector.class,TTTImportBeanDefinitionRegistrar.class})
public class MainConfig {
@Bean("person")
public Person zhangsan(){
System.out.println("给我们的容器中添加张三");
return new Person("张三",22);
}
@Bean(initMethod = "init",destroyMethod = "destory")
public Bike bike(){
return new Bike();
}
}
package test;
import com.enjoy.cap7.MainConfig;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* FactoryBean 和 BeanFactorty 有什么区别?
*
* FactoryBean :可以把我们的JAVA实例通过FactoryBean注入到容器中
*
* BeanFactorty:从我们的容器中获取实例化后的bean
*
*/
public class MainTEwst7 {
@Test
public void sss(){
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
System.out.println("容器起用完成");
}
}
在默认情况下spring创建bean是单例模式,单例模式在创建容器的同事加入bean实例。
如上打印结果我们可以到打印出了 bean的新建 初始化的时候的打印日志
当我们再test用例里面加入如下一句话 就是关闭容器的时候 :
annotationConfigApplicationContext.close();
打印日志如下:
我们可以看到日志中打印了destory的执行日志(当然这只是一个演示)
那么我们看一下close方法
销毁缓存中所有的单例的bean