Accessing spring beans in static method

前端 未结 8 637
清酒与你
清酒与你 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:51

    you may also implement ApplicationContextAware interface, like this:

    @Component
    public class TestUtils implements ApplicationContextAware {
    
      private static ApplicationContext ac;
    
      public static String getBeanDetails() {
        return beanName = ((TestBean) ac.getBean("testBean")).getDetails();
      }
    
      @Override
      public void setApplicationContext(ApplicationContext ac) {
        TestUtils.ac = ac;
      }
    
    }
    

提交回复
热议问题