目录
1、static比InitializingBean先执行
@Service
public class KmsService implements InitializingBean {
public static final Logger LOGGER = LoggerFactory.getLogger(KmsService.class);
private static List<String> list = Lists.newArrayList();
@Override
public void afterPropertiesSet() throws Exception {
LOGGER.info("afterPropertiesSet start...");
System.out.println(list);
}
static{
LOGGER.info("static start...");
list.add("1");
list.add("2");
}
//static start...
//afterPropertiesSet start...
// [1, 2]
}
@Component
public class KmsInfo implements InitializingBean{
private static final String APP_KEY = "com.aaa";
private static final String NAME = "privateInfo.des";
private static final boolean IS_PAY = false;
private static String pwd;
private static final Logger LOGGER = LoggerFactory.getLogger(KmsInfo.class);
private KmsInfo(){}
static {
try {
pwd = Kms.getByName(APP_KEY, NAME, IS_PAY);
}catch (Exception e){
LOGGER.error("获取秘钥异常 exception:{}", ExceptionUtils.getStackTrace(e));
}
}
public static String getPwd() {
return pwd;
}
@Override
public void afterPropertiesSet() throws Exception {
if (StringUtils.isBlank(pwd)){
throw new Exception("获取秘钥异常");
}
LOGGER.info("获取秘钥成功");
}
}
2、初始化的顺序是:
Constructor > @PostConstruct > InitializingBean > init-method
/**
常用的设定方式有以下三种:
通过实现 InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;
通过 <bean> 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法;
在指定方法上加上@PostConstruct 或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用。
*/
public class InitSequenceBean implements InitializingBean {
public InitSequenceBean() {
System.out.println("InitSequenceBean: constructor");
}
@PostConstruct
public void postConstruct() {
System.out.println("InitSequenceBean: postConstruct");
}
public void initMethod() {
System.out.println("InitSequenceBean: init-method");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitSequenceBean: afterPropertiesSet");
}
}
并且在配置文件中添加如下Bean定义:<bean class="InitSequenceBean" init-method="initMethod"></bean>
输出结果:
InitSequenceBean: constructor
InitSequenceBean: postConstruct
InitSequenceBean: afterPropertiesSet
InitSequenceBean: init-method
总结:
- spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中同过init-method指定,两种方式可以同时使用
- 实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖
- 如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。