作用
标注了@PostConstruct的方法会在对象实例化并完成所有依赖注入之后调用。
用于实现类内部资源的初始化工作,比如打开数据库连接、加载配置信息、预处理数据结构等。
参考:@PostConstruct注解详解
特点
可替代构造函数:
由于构造函数中不能直接使用依赖注入的对象,因此@PostConstruct注解提供了一个明确的初始化阶段,在这个阶段可以安全地访问那些由容器注入的所有依赖属性。
例子
如果觉得还不清楚我这儿举个例子,比如我有个需求时当我的spring容器启动起来之后我想默认的将我的字典数据加入redis缓存中,当然实现这个需求的方法很多,我们看一下用@PostConstruct注解怎么实现。
首先我写了一个缓存配置类CacheConfig和一个DictService业务类来模拟这个过程。
CacheConfig配置类
package com.example.springtest.postConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.List;
@Configuration
public class CacheConfig {
@Autowired
private DictService dictService;
public CacheConfig() {
System.out.println("初始化CacheConfig");
}
@PostConstruct
private void init(){
List<Object> allDict = dictService.getAllDict();
System.out.println("将字典数据存入redis");
}
}
这个类一旦被实例化之后,就会将调用@PostConstruct修饰的方法进行缓存的存入,那为什么我们不在构造方法中直接去存入缓存,原因就在于在构造方法中DictService 还没有被注入,所以还不能使用,@PostConstruct修饰的方法是在注入之后执行的。
package com.example.springtest.postConstruct;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Service
public class DictService {
public List<Object> getAllDict(){
//模拟查询数据库
System.out.println("获取所有字典参数");
List<Object> list = Arrays.asList("1","2","3");
return list;
}
}