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

3 Answers

up vote 38 down vote accepted

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.

  • Interesting trick. I'll keep that in mind for the future :) –  T.G  Mar 23 '14 at 14:39
  • The return type of the method MUST be void. docs.oracle.com/javaee/5/api/javax/annotation/… –  Dušan Knežević  Jun 12 '14 at 11:44 
  • 1
    Long after the battle, I've come to use this solution which works for the most part. But the company Sonar quickly gave me a warning about it : Correctly updating a static field from a non-static method is tricky to get right and could easily lead to bugs if there are multiple class instances and/or multiple threads in play. Ideally, static fields are only updated from synchronized static methods. I thought it'd worthy to mention it. –  MaxouMask  Jan 19 '17 at 9:42 
  • Documentation says The method on which PostConstruct is applied MAY be public, protected, package private or private. so I think initStaticDao() could be private just so nobody has to see it when using code completion etc. –  spoko  Mar 27 '17 at 15:28
  • @spokoThanks for the comment. –  Weibo Li  Aug 15 '17 at 9:46
  • @WeiboLi :- I try to Implement the same thing,I wanted to pick the values from bootstrap.yml file. All the @values are configured in CosmosConnection class. Here is my code static CosmosConnection cosmos= new CosmosConnection(); @Autowired private CosmosConnection tcosmos; @PostConstruct public void init() { SupplierGetResponseFeed.cosmos = tcosmos; } In the same class I have another method from where I am calling cosmos.connectToDB(); –  Anand Deshmukh Apr 9 at 15:16

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.

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

猜你喜欢

转载自blog.csdn.net/zilaike/article/details/80061417
今日推荐