@Autowired 在静态类中 [英] @Autowired in static classes
问题描述
这是一个带有 Hibernate 的 Spring MVC 项目.我正在尝试创建一个 Logger 类,负责将日志输入到数据库中.其他类只是调用具有某些属性的适当方法,而这个类应该可以发挥所有作用.本质上它应该是一个带有静态方法的类,但这会导致自动装配 dao 对象出现问题.
This is an Spring MVC project with Hibernate. I'm, trying to make a Logger class that, is responsible for inputting logs into database. Other classes just call proper methods with some attributes and this class should do all magic. By nature it should be a class with static methods, but that causes problems with autowiring dao object.
public class StatisticLogger {
@Autowired
static Dao dao;
public static void AddLoginEvent(LogStatisticBean user){
//TODO code it god damn it
}
public static void AddDocumentEvent(LogStatisticBean user, Document document, DocumentActionFlags actionPerformed){
//TODO code it god damn it
}
public static void addErrorLog(Exception e, String page, HashMap<String, Object> parameters){
ExceptionLogBean elb=new ExceptionLogBean();
elb.setStuntDescription(e);
elb.setSourcePage(page);
elb.setParameters(parameters);
if(dao!=null){ //BUT DAO IS NULL
dao.saveOrUpdateEntity(elb);
}
}
如何做对?我应该怎么做才能使 dao 对象为空?我知道我可以将它作为方法参数传递,但这不是很好.我猜自动装配不能在静态对象上工作,因为它们很早就被创建了,自动装配机制还没有被创建.
How to make it right? What should I do not to make dao object null? I know that I could pass it as a method parameter, but that isn't very good. I'm guessing that autowired can't work on static objects, because they are created to early to autowiring mechanism isn't created yet.
推荐答案
你不能@Autowired
一个静态字段.但是有一个棘手的技巧来处理这个:
You can't @Autowired
a static field. But there is a tricky skill to deal with this:
@Component
public class StatisticLogger {
private static Dao dao;
@Autowired
private Dao dao0;
@PostConstruct
private void initStaticDao () {
dao = this.dao0;
}
}
一言以蔽之,@Autowired
一个实例字段,在你的对象被构造的时候赋值给静态字段.顺便说一句,StatisticLogger
对象也必须由 Spring 管理.
In one word, @Autowired
a instance field, and assign the value to the static filed when your object is constructed. BTW, the StatisticLogger
object must be managed by Spring as well.
这篇关于@Autowired 在静态类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!