Accessing spring beans in static method

前端 未结 8 621
清酒与你
清酒与你 2020-12-23 16:17

I have a Util class with static methods. Inside my Util class, I want to use spring beans so I included them in my util class. As far as I know it\'s not a good practice to

8条回答
  •  伪装坚强ぢ
    2020-12-23 16:50

    My approach is for the bean one wishes to access to implement InitializingBean or use @PostConstruct, and containing a static reference to itself.

    For example:

    @Service
    public class MyBean implements InitializingBean {
        private static MyBean instance;
    
        @Override
        public void afterPropertiesSet() throws Exception {
            instance = this;
        }
    
        public static MyBean get() {
            return instance;
        }
    }
    

    Usage in your static class would therefore just be:

    MyBean myBean = MyBean.get();
    

    This way, no XML configuration is required, you don't need to pass the bean in as a constructor argument, and the caller doesn't need to know or care that the bean is wired up using Spring (i.e., no need for messy ApplicationContext variables).

提交回复
热议问题