Accessing spring beans in static method

前端 未结 8 587
清酒与你
清酒与你 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 17:05

    This worked for me.

    Define your bean using xml configuration (old school):

    <bean id="someBean1" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"><value>${db.driver}</value></property>     
        <property name="url"><value>${db.url}</value></property>
        <property name="username"><value>${db.username_seg}</value></property>
        <property name="password"><value>${db.password_seg}</value></property>
    </bean> 
    

    Or define it with java instead xml (new school)

    @Bean(name = "someBean2")
    public MySpringComponent loadSomeSpringComponent() {
    
      MySpringComponent bean = new MySpringComponent();
      bean.setSomeProperty("1.0.2");
      return bean;
    }
    

    Accessing spring bean in static method

    import org.springframework.web.context.ContextLoader;
    import org.springframework.web.context.WebApplicationContext;
    
    public class TestUtils {
    
      public static void getBeansFromSpringContext() {
        WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
        //for spring boot apps
        //ApplicationContext context = SpringApplication.run(Application.class, args)
        DataSource datasource  = (DataSource)context.getBean("someBean1");
        MySpringComponent springBean  = (MySpringComponent)context.getBean("someBean2");
      }
    }   
    

    HTH

    0 讨论(0)
  • 2020-12-23 17:05

    This is how I injected from spring for a static field.

    <bean id="..." class="...">
     <property name="fieldToBeInjected">
                <util:constant static-field="CONSTANT_FIELD" />
            </property>
    </bean>
    

    Maybe this will help you, as well.

    0 讨论(0)
提交回复
热议问题