@PostConstruct是java5的时候引入的注解,指的是在项目启动的时候执行这个方法,也可以理解为在spring容器启动的时候执行,
类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。相当于init-mehtod
<bean id="idService" class="com.robert.vesta.service.factory.IdServiceFactoryBean"
init-method="init">
<property name="providerType" value="PROPERTY"/>
<property name="type" value="${vesta.type}"/>
<property name="genMethod" value="${vesta.genMethod}"/>
<property name="machineId" value="${vesta.machine}"/>
</bean>
可作为一些数据的常规化加载,比如数据字典之类的。
@PostConstruct
protected void init() {
try {
log.debug("AppInition.initialize() Start...");
Map configMap= iSystemConfigService.getConfigMap();
ReflectUtil.reflectProperties(configMap,AppInitConstants.class);
log.debug("AppInition.initialize() End...");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
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 id="initSequenceBean " class="com.example.InitSequenceBean" init-method="initMethod"/>
输出:
InitSequenceBean: constructor
InitSequenceBean: postConstruct
InitSequenceBean: afterPropertiesSet
InitSequenceBean: init-method
通过上述输出结果,三者的先后顺序也就一目了然了:
Constructor > @PostConstruct > InitializingBean > init-method
@PreDestroy说明
类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行