Bean定义
public class Car {
public Car() {
System.out.println("car constructor");
}
public void init(){
System.out.println("car init");
}
public void destroy(){
System.out.println("car destroy");
}
}
配置类
bean创建--初始化--销毁
可以自定义初始化和销毁方法
初始化:对象创建完成,并赋值完成,调用初始化方法
销毁: 容器关闭进行销毁(单实例)
? 多实例容器不会管理这个bean
@Configuration
public class MyCOnfigOfLifeCycle {
@Bean(initMethod = "init",destroyMethod = "destroy")
public Car car(){
return new Car();
}
}
获取容器
@Test
public void test01(){
printBeans(applicationContext);
// 关闭容器
applicationContext.close();
}
private void printBeans(AnnotationConfigApplicationContext applicationContext){
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
System.out.println(beanDefinitionName);
}
}
Bean定义
public class Cat implements InitializingBean, DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("cat destroy");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("cat initialize");
}
}
实现了InitializingBean和Disposable后,也可以实现初始化和销毁的方法
Bean定义
public class Dog {
public Dog(){
System.out.println("dog constructor");
}
@PostConstruct
public void init(){
System.out.println("dog init");
}
@PreDestroy
public void destroy(){
System.out.println("dog destroy");
}
}
bean
定义
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("before init" + beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("after init" + beanName);
return bean;
}
}
加入到bean中,可以发现每个bean初始化前后都会执行功能
afterPropertiesSet()
方法或bean对应的init-method之前afterPropertiesSet()
方法或对应init-method方法之后。postProcessBeforeInitialization方法的返回值会被Spring容器作为处理后的Bean注册到容器中。如果你在postProcessBeforeInitialization方法中重新构造了一个Bean进行返回,而不是返回参数中的bean;那么你返回的Bean将会被注册到Spring容器中。而原来在Spring中配置的Bean(被Spring实例化的Bean)将会被覆盖。
一旦这两个方法返回null,就不会执行后面的postProcessBefore/AfterInitialization,(在applyBeanPostProcessorsBeforeInitialization中)
for(Iterator var4 = this.getBeanPostProcessors().iterator(); var4.hasNext(); result = current) {
BeanPostProcessor processor = (BeanPostProcessor)var4.next();
current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
}
步骤:
populateBean给Bean赋值
initializeBean{ applyBeanPostProcessorsBeforeInitialization,
? invokeInitMethods, // 自定义初始化
? applyBeanPostProcessorsAfterInitialization}
bean赋值,bean注入,@autowire,生命周期注解功能,@Async
原文:https://www.cnblogs.com/jimmyhe/p/13661809.html