@autowired in static classes

最后都变了- 提交于 2019-11-26 11:06:45

问题


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 autowiering 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);
    }
}

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 autowiering mechanism isn\'t created yet.


回答1:


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;
  }

}

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.




回答2:


Classical autowiring probably won't work, because a static class is not a Bean and hence can't be managed by Spring. There are ways around this, for example by using the factory-method aproach in XML, or by loading the beans from a Spring context in a static initializer block, but what I'd suggest is to change your design:

Don't use static methods, use services that you inject where you need them. If you use Spring, you might as well use it correctly. Dependency Injection is an Object Oriented technique, and it only makes sense if you actually embrace OOP.




回答3:


I know this is an old question but just wanted to share what I did, the solution by @Weibo Li is ok but the problem it raises Sonar Critical alert about assigning non static variable to a static variable

the way i resolved it with no sonar alerts is the following

  1. I change the StatisticLogger to singlton class (no longer static) like this

    public class StatisticLogger { private static StatisticLogger instance = null; private Dao dao;

    public static StatisticLogger getInstance() {
        if (instance == null) {
            instance = new StatisticLogger();
        }
        return instance;
    }
    
    protected StatisticLogger() {
    }
    
    public void setDao(Dao dao) {
        this.dao = dao;
    }
    public void AddLoginEvent(LogStatisticBean user){
        //TODO code it god damn it
    }
    public void AddDocumentEvent(LogStatisticBean user, Document document, DocumentActionFlags actionPerformed){
        //TODO code it god damn it
    }
    public  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){ 
            dao.saveOrUpdateEntity(elb);
    }
    

    }

  2. I created a service(or Component) that autowire the service that i want and set it in the singlton class This is safe since in spring it will initialize all the managed beans before doing anything else and that mean the PostConstruct method below is always called before anything can access the StatisticLogger something like this

    @Component public class DaoSetterService {

    @Autowired
    private Dao dao0;
    
    @PostConstruct     
    private void setDaoValue () {
        StatisticLogger.getInstance().setDao(dao0);
    }
    

    }

  3. Instead of using StatisticLogger as static class I just use it as StatisticLogger.getInstance() and i can access all the methods inside it



来源:https://stackoverflow.com/questions/11392692/autowired-in-static-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!