简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM