springhibernatespring-mvcautowiredstatic-classes

@Autowired in static classes


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

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.


Solution

  • 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.