场景:在工具类中,有时候我们需要给静态成员变量注入值,而静态成员变量实在类加载的时候加载的。
我们通常有两种方法去实现:
1:使用set函数注入
@Component
public Class LogUtil {
private static LogStampService logStampService;
@Autowired
public void setService(LogStampService logStampService) {
LogUtil.logStampService = logStampService;
}
}
2:使用@PostConstruct注解
@Component
public Class LogUtil {
@Autowired
private LogStampService logStampService;
private static LogStampService logStampSer;
@PostConstruct
public void init() {
logStampSer = this.logStampService;
}
}