@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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值