Spring InitialzingBean与@PostConstruct用法
前言
spring的InitialzingBean 接口有很好的好处,位于Spring beans中,它只提供一个方法afterPropertiesSet(),当你实现了该方法后,spring就会对你的提供框架级的支持,当你通过spring容器生产出实现了该接口的类的实例后,它就会调用afterPropertiesSet(),通过这个方法,你可以检查你的bean是否正确地被初始化了,当然,你也可以用init-method方法,这两种方式可以同时使用,调用的顺序为init-method后调用。
Spring initialzingBean使用方法
@Component
@Data
public class TempReaderConfig implements InitializingBean {
private Set<String> tempList = Sets.newHashSetWithExpectedSize(243);
@Override
public void afterPropertiesSet() throws Exception {
//读取配置文件
processRead();
//写入文件
// processW();
}
@PostConstruct使用
/**
* 从Java EE 5规范开始
* @PostConstruct:@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。
* PostConstruct在构造函数之后执行,init()方法之前执行。@PreDestroy 注解的方法在destroy()方法执行执行之后执行
*/
@PostConstruct
public void init(){
String configFile = "post_code.yml";
Resource resource = new ClassPathResource(configFile);
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream(), "UTF-8"), 8192)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
postCodeSet.add(StringUtils.trim(line));
}
} catch (IOException e) {
logger.warn("resource read error : {}",e);
}
}
总结
总结:
1:spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中同过init-method指定,两种方式可以同时使用
2:实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖
3:如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。