@PostConstruct注解详解

初始化方式

假设类DrawConfig有个成员变量IDrawAlgorithm被@Resource修饰,那么IDrawAlgorithm的注入是在DrawConfig的构造方法之后执行的。

如果想在DrawConfig对象生成时候完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入的对象,那么就无法在构造函数中实现(ps:spring启动时初始化异常),例如:

public class DrawConfig {


    @Resource
    private IDrawAlgorithm defaultRateRandomDrawAlgorithm;

    @Resource
    private IDrawAlgorithm singleRateRandomDrawAlgorithm;


    protected static Map<Integer,IDrawAlgorithm> drawAlgorithmMap = new ConcurrentHashMap<>();


    //@PostConstruct注解的方法将会在DrawAlgorithm注入完成后被自动调用。
    @PostConstruct
    public void init(){
        drawAlgorithmMap.put(1,defaultRateRandomDrawAlgorithm);
        drawAlgorithmMap.put(2,singleRateRandomDrawAlgorithm);
    }
}

因此,可以使用@PostConstruct注解来完成初始化,@PostConstruct注解的方法将会在IDrawAlgorithm注入完成后被自动调用。

  总结:类初始化调用顺序:

(1)构造方法Constructor

(2)@Autowired

(3)@PostConstruct

初始化方式二:实现InitializingBean接口


public class DrawConfig implements InitializingBean {


    @Resource
    private IDrawAlgorithm defaultRateRandomDrawAlgorithm;

    @Resource
    private IDrawAlgorithm singleRateRandomDrawAlgorithm;


    protected static Map<Integer,IDrawAlgorithm> drawAlgorithmMap = new ConcurrentHashMap<>();



    @Override
    public void afterPropertiesSet() throws Exception {
        drawAlgorithmMap.put(1,defaultRateRandomDrawAlgorithm);
        drawAlgorithmMap.put(2,singleRateRandomDrawAlgorithm);
    }

        比较常见的如SqlSessionFactoryBean,它就是通过实现InitializingBean完成初始化的。

@Override
public void afterPropertiesSet() throws Exception {
 // buildSqlSessionFactory()是完成初始化的核心方法,必须在构造方法调用后执行
 this.sqlSessionFactory = buildSqlSessionFactory(); 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值