Spring Bean的生命周期图如上所示。具体内如如下:
- Spring容器从XML文件或@Configuration中bean的定义中实例化bean对象。
- Spring依据配置中指定的属性,为bean填充所有属性,此时是插入属性,但并没有对属性赋值。
- 如果bean实现BeanNameAware接口,spring调用setBeanName()方法,并传递bean的id。
- 如果bean实现BeanFactoryAware接口,spring将调用setBeanFactory()方法,并把自己作为参数。
- 如果bean实现ApplicationContextAware接口,spring将调用setApplicationContext()方法,并把ApplicationContext实例作为参数。
- 如果存在与bean关联的任何BeanPostProcessors(后处理器),则调用preProcessBeforeInitialization()方法。比如Autowired等依赖注入功能是在此时完成,此时已经对属性完成赋值,因此在此步骤之后的接口实现中,可以各个已经赋值的属性进行值的修改,或者利用属性传入其他方法中。
- 如果Bean实现了InitializingBean接口,则调用bean的afterPropertiesSet()方法。一般常在此调用bean对象内的属性值!看下面例子:
@Data //get、set方法
@Slf4j //记录日志
@ConfigurationProperties(prefix = "ly.jwt") //获取配置文件中的“ly.jwt”下的属性
@Component
public class JwtProperties implements InitializingBean {
//这里会从yml配置文件中获得公钥和私钥的路径值,但由于每次使用公钥和私钥都需要从路径也就是硬盘上读取,效率过低,于是需要在本配置类中直接获取公钥和私钥对象
private String pubKeyPath;
private String priKeyPath;
//定义公钥和私钥对象,然后考虑公钥和私钥的路径值是何时被赋值的,在此之后才可以取其值生成公钥和私钥对象
private PrivateKey privateKey;
private PublicKey publicKey;
//根据Spring创建bean的生命周期,InitializingBean下的afterPropertiesSet方法是在依赖注入后执行,此时yml中的属性值已经注入到本配置文件的成员属性中,可直接获取其值
@Override
public void afterPropertiesSet() throws Exception {
//此时pubKeyPath和priKeyPath均被附上路径值,可调用rsa工具类获取公钥和私钥
try {
privateKey = RsaUtils.getPrivateKey(priKeyPath);
publicKey = RsaUtils.getPublicKey(pubKeyPath);
} catch (Exception e) {
e.printStackTrace();
log.error("【授权中心解析公钥和私钥失败】", e.getMessage());
}
}
}
- 如果为bean指定了init-method,那么将调用bean的init方法。
- 最后,如果存在与bean关联的任何BeanPostProcessors,则将调用postProcessAfterInitialization()方法。