Accessing spring beans in static method

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

    The approach you have outlined is what I have seen being used to inject a Spring bean into a utility class.

    
     
    
    

    Another option is:

    
            
            
                
                    
                
           
    
    

    with:

    public class TestUtils {
    
       private static testBean;
    
       public static void setInstance(TestBean anInstance) {
         testBean = anInstance;
       }
    
      public static String getBeanDetails() {
        return testBean.getDetails();
      }
    }
    

    More details are here and here

提交回复
热议问题