A D
A D

Reputation: 307

Spring ClassPathXmlApplicationContext creating an empty instance of all beans in spring conf file?

I m playing with Spring. I created a Spring beans file:

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

 <context:annotation-config />
<context:component-scan   base-package="hibernate.entities" />

    <bean id="sicknessLeprosa" class="hibernate.entities.Sickness"  init-method="print"  scope="prototype">
<property name="nom" value="Leprosa" />
</bean>
<bean id="sicknessSclerosa" class="hibernate.entities.Sickness"  init-method="print"  scope="prototype">
<property name="nom" value="Sclerosa" />
</bean>

</beans>

When I call:

ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Module-Annotations.xml");
Map<String, Sickness> SicknessList = context.getBeansOfType(Sickness.class);
System.out.println("Number of ISickness beans: " + SicknessList.size() );
for(Entry<String, Sickness> entry : SicknessList.entrySet() ){
System.out.print(entry.getKey() + ": ");
entry.getValue().print();
}

I get this output:

Number of ISickness beans: 3
sickness: undefined sickness
sicknessLeprosa: Leprosa
sicknessSclerosa: Sclerosa

Where does the first occurence come from????????????? It looks it comes from :

new ClassPathXmlApplicationContext("Spring-Module-Annotations.xml");

which seems to create an instance of Sickness when invoked.

Thx in advance

Upvotes: 1

Views: 508

Answers (1)

Sergi Almar
Sergi Almar

Reputation: 8404

As you are using component scanning this will scan your base package recursively and try to find classes annotated with stereotype annotations (such as @Component, @Service, @Repository...). I guess your Sickness class is annotated with one of these. In that case the container will initialize it and that's why you get the first bean. The other two beans are explicitly defined in the configuration class.

BTW, you don't need <context:annotation-driven/> if you are using <context:component-scan />

Upvotes: 2

Related Questions