views:

361

answers:

2

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 us to inject a value for this static property?

+2  A: 

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

JoseK
+3  A: 

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.

Espen