SpringBean生命周期
导入相关依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
创建测试bean,此类实现了InitializingBean,BeanNameAware,DisposableBean 三个接口**
@Component(value = "user")
@Getter
@Setter
public class User implements InitializingBean, BeanNameAware, DisposableBean {
private String name;
private Integer age;
public User() {
System.out.println("调用了构造器");
this.name = "xxx";
this.age = 12;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean.afterPropertiesSet调用");
}
@Override
public void setBeanName(String s) {
System.out.println("调用了setBeanName");
}
@Override
public void destroy() throws Exception {
System.out.println("调用了destroy方法");
}
}
方便起见,创建配置类,不使用XML方式进行扫描
@Configuration
@ComponentScan(basePackages = {"com.wjs.Spring"})
public class Config {
}
创建MyPostProcceser类实现BeanPostProcessor接口
@Component
public class MyPostProcceser implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
//避免Config类注入时与调用方法与结果产生歧义
if("user".equals(beanName)){
System.out.println("执行了MyPostProcceser.postProcessBeforeInitialization");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if("user".equals(beanName)){
System.out.println("执行了MyPostProcceser.postProcessAfterInitialization");
}
return bean;
}
}
编写测试类
public class test2 {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
User user = context.getBean("user", User.class);
System.out.println(user);
user.destroy();
}
}
结果如下
总结
- Bean 容器找到配置文件中 Spring Bean 的定义。
- Bean 容器利用 Java Reflection API 创建一个 Bean 的实例。
- 如果涉及到一些属性值 利用 set()方法设置一些属性值。
- 如果 Bean 实现了 BeanNameAware 接口,调用 setBeanName()方法,传入 Bean 的名字。
- 如果 Bean 实现了 BeanClassLoaderAware 接口,调用 setBeanClassLoader()方法,传入 ClassLoader对象的实例。
- 与上面的类似,如果实现了其他 *.Aware接口,就调用相应的方法。
- 如果有和加载这个 Bean 的 Spring 容器相关的 BeanPostProcessor 对象,执行postProcessBeforeInitialization() 方法
- 如果 Bean 实现了InitializingBean接口,执行afterPropertiesSet()方法。
- 如果 Bean 在配置文件中的定义包含 init-method 属性,执行指定的方法。(本次没有使用xml)
10.当要销毁 Bean 的时候,如果 Bean 实现了 DisposableBean 接口,执行 destroy() 方法。