saurabh kumar
saurabh kumar

Reputation: 164

Autowire annotation giving null value in spring

    public class Address {

        String street;
       //set &get
    }


     public class Person {

            int id;

            String name;

             @Autowired
            Address address; 
       //set &get
}

xml

<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-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:annotation-config />

<bean id="Address" class="bean.Address">  
<property name="street" value="baglur"></property>  
</bean>  


<bean id="Person" class="bean.Person" autowire="byType"  >  
<property name="id" value="786"></property>
<property name="name" value="saurabh"></property>


</bean>  

</beans>

test

public class Test {
    public static void main(String[] args) {  
        Resource resource=new ClassPathResource("applicationContext.xml");  
        BeanFactory factory=new XmlBeanFactory(resource);  
          Person p = (Person)factory.getBean("Person");
        System.out.println(p.getInfo()); 
    } 

Here i am trying the @Autowire annotation to achieve autowire byType feature ,but i am getting null value for the address but using autowire ="byType" i am getting proper output.What's wrong here?

Upvotes: 0

Views: 447

Answers (1)

Ori Dar
Ori Dar

Reputation: 19000

That's because you are using the deprecated XmlBeanFactory It doesn't activate annotations bean post processors (specifically: AutowiredAnnotationBeanPostProcessor), so <context:annotation-config /> is ignored in essence.

Changing

BeanFactory factory=new XmlBeanFactory(resource);

to

BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml");

solves the problem.

Comment: in order for autowire by name strategy to work, you should camel case your bean names, address and person in that case.

Upvotes: 3

Related Questions