Can you use @Autowired with static fields?

后端 未结 11 1345
臣服心动
臣服心动 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条回答
  • 2020-11-22 13:29

    Create a bean which you can autowire which will initialize the static variable as a side effect.

    0 讨论(0)
  • 2020-11-22 13:34

    Init your autowired component in @PostConstruct method

    @Component
    public class TestClass {
       private static AutowiredTypeComponent component;
    
       @Autowired
       private AutowiredTypeComponent autowiredComponent;
    
       @PostConstruct
       private void init() {
          component = this.autowiredComponent;
       }
    
       public static void testMethod() {
          component.callTestMethod();
       }
    }
    
    0 讨论(0)
  • 2020-11-22 13:35

    You can achieve this using XML notation and the MethodInvokingFactoryBean. For an example look here.

    private static StaticBean staticBean;
    
    public void setStaticBean(StaticBean staticBean) {
       StaticBean.staticBean = staticBean;
    }
    

    You should aim to use spring injection where possible as this is the recommended approach but this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.

    Note testing can also be more difficult with this approach.

    0 讨论(0)
  • 2020-11-22 13:39

    In short, no. You cannot autowire or manually wire static fields in Spring. You'll have to write your own logic to do this.

    0 讨论(0)
  • 2020-11-22 13:41
    @Component("NewClass")
    public class NewClass{
        private static SomeThing someThing;
    
        @Autowired
        public void setSomeThing(SomeThing someThing){
            NewClass.someThing = someThing;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 13:41
    private static UserService userService = ApplicationContextHolder.getContext().getBean(UserService.class);
    
    0 讨论(0)
提交回复
热议问题