Spring InitialzingBean与@PostConstruct用法

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指定的方法。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌兮~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值