Autowire注释在spring中给出null值

时间:2015-11-21 07:35:49

标签: java 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>

测试

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()); 
    } 

这里我尝试@Autowire注释来实现autowire byType功能,但我得到地址的空值,但使用autowire =&#34; byType&#34;我得到了正确的输出。这里有什么问题?

1 个答案:

答案 0 :(得分:3)

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.

相关问题