@PostConstruct
注解是java自带的。Spring框架对改注解进行了解析,解析的类是CommonAnnotationBeanPostProcessor
,它是一个后置处理器。
需要注意的是,这个注解只能使用在无参无返回的方法上,且一个类只能使用一次。
被注解的方法,在该类全局变量注入完成后,立即被调用,且只调用一次。大致的调用顺序是:
构造器–>@Autowired—>@PostConstruct—>init()
有点类似static代码块,不同在于,static代码块会在构造器之前运行。
根据@PostConstruct执行的时机,写工具类的时候,可以使用。如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class RedisUtil {
private static RedisTemplate<Object, Object> redisTemplates;
@Autowired
private RedisTemplate<Object, Object> redisTemplate;
@PostConstruct
public void initialize() {
redisTemplates = this.redisTemplate;
}
/**
* 添加元素
*
* @param key
* @param value
*/
public static void set(Object key, Object value) {
if (key == null || value == null) {
return;
}
redisTemplates.opsForValue().set(key, value);
}
}
不用实现ApplicationContextAware接口,即可拿到所需要的bean。