Injecting values for static constants in Spring

前端 未结 2 1811
借酒劲吻你
借酒劲吻你 2020-12-09 11:09

In one of my classes there is a public static String member and I need set this value in the applicationContext.xml! That is, is it possible for u

相关标签:
2条回答
  • 2020-12-09 11:22

    No, it's not possible to inject a value to a static field from your XML context.

    If you can modify the class, you have the following simple choices:

    • remove the static modifier and add @Inject/@Autowire above the field
    • add a constructor/setter/init method.

    Else, you can do it with Spring's Java configuration support.

    An example:

    The Demo class with the static field and a JUnit method that asserts that the Spring container injects the wanted value into the static field:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("test-context.xml")
    public class Demo {
    
        public static String fieldOne;
    
        @Test
        public void testStaticField() {
            assertEquals("test", fieldOne);     
        }
    }
    

    Add the context namespace to your applicationContext and component-scan element:

    <context:component-scan base-package="com.example" />
    

    Add your bean with the static field like the this:

    @Configuration
    public class JavaConfig {
    
        @Bean
        public Demo demo() {
            Demo.fieldOne = "test";
    
            return new Demo();
        }
    }
    

    In this case, the JavaConfig class must be in the com.example package as declared in the component-scan element.

    0 讨论(0)
  • 2020-12-09 11:23

    yes there is an example on this link http://planproof-fool.blogspot.com/2010/03/spring-setting-static-fields.html

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