Can you use @Autowired with static fields?

后端 未结 11 1529
臣服心动
臣服心动 2020-11-22 13:15

Is there some way to use @Autowired with static fields. If not, are there some other ways to do this?

11条回答
  •  -上瘾入骨i
    2020-11-22 13:45

    Generally, setting static field by object instance is a bad practice.

    to avoid optional issues you can add synchronized definition, and set it only if private static Logger logger;

    @Autowired
    public synchronized void setLogger(Logger logger)
    {
        if (MyClass.logger == null)
        {
            MyClass.logger = logger;
        }
    }
    

    :

提交回复
热议问题