1. InitializingBean
- 这个接口 InitailizingBean中只有一个方法,就是afterPropertiesSet。该方法是指Spring容器在启动后主动调用该接口的方法。
- 如果一个Bean实现了InitializingBean,则该方法会在容器实例化该Bean,初始化Bean的属性完毕之后,再调用afterPropertiesSet方法。
- afterPropertiesSet通过方法名称即可知道含义:在bean的属性设置完毕后调用该方法。
接口InitializingBean接口源码如下:
public interface InitializingBean {
/**
* 当Bean的属性被设置完毕后,由BeanFactory调用该方法。
* 该方法允许bean的实例去执行一些初始化动作,当所有的bean属性完成设置之后执行。
*/
void afterPropertiesSet() throws Exception;
}
2. ApplicationContextWare
- 名称带Aware,就可以知道这个接口由Spring容器主动通知调用。Spring容器在通知该接口的实现类时,会将上下文ApplicationContext注入进来。
- 接口中就一个方法:
void setApplicationContext(ApplicationContext applicationContext) throws BeansException - 即容器启动后,将ApplicationContext 注入到该方法中。
接口ApplicationContextWare源码如下:
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext var1) throws BeansException;
}
3. 例子
- 3.1 枚举类FamilyEnum
package com.example.demo.blogTest;
public enum FamilyEnum {
FATHER(45, "father"),
MOTHER(42, "mother"),
SON(18, "son");
private Integer age;
private String name;
FamilyEnum(Integer age, String name) {
this.age = age;
this.name = name;
}
public Integer getAge() {
return age;
}
public String getName() {
return name;
}
}
- 3.2 自定义注入类FamilyHolder
package com.example.demo.blogTest