shrewquest
shrewquest

Reputation: 561

while using Spring ApplicationContext as in the example below, are annotations taken care of

public class SomeClass {
    @Autowired
    public WaterContainer wc;

    private static int count = 0;

    SomeClass(){ ++count;}

    public static int testmethod() {
        return count;
    }

    public static void main(String[] args) {
        ApplicationContext context = new FileSystemXmlApplicationContext("spring-configuration\\beans.xml");

        SomeClass obj = context.getBean(SomeClass.class);
        //SomeClass obj2 = new SomeClass();
        System.out.println("value of count "+SomeClass.testmethod());
        if(obj.wc != null)
            System.out.println("wc volume "+obj.wc.getCurrentVolume());
        else
            System.out.println("wc bean "+context.getBean(WaterContainer.class).getCurrentVolume()); //+(obj.wc==null)
    }
}

The beans.xml file contains this :

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean class="com.app.data.SomeClass"/>
    <bean class="com.app.mechanism.WaterContainer">
        <constructor-arg value="30"/>
    </bean>

</beans>

the output that I got was as below but I expected the field wc in the SomeClass object to not be null, does that mean autowired annotations are not taken care of? or have I gone wrong somewhere?
value of count 1
wc bean 30

If so then how does
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"file:spring-configuration\\beans.xml"})
work for unit testing? how is the autowiring taken care of here

Upvotes: 0

Views: 252

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280054

As M. Deinum stated, annotation configuration is built into some ApplicationContext implementations and not in others.

FileSystemXmlConfiguration is an implementation that does not have annotation configuration built into it. You can enable that annotation configuration with

<context:annotation-config />

(and the relevant namespace declarations).

Since that configuration was not enabled, @Autowired fields were not processed, and your SomeClass#wc field was left null.

The test configuration you've shown internally uses an AnnotationConfigApplicationContext where annotation configuration is built in.

Upvotes: 1

Related Questions