[英]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>
测试
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批注以实现自动装配byType功能,但是我获得的地址为空值,但是使用自动装配=“ byType”我得到了正确的输出。这是怎么回事?
那是因为您正在使用不推荐使用的XmlBeanFactory
它不会激活注释bean后处理器(特别是: AutowiredAnnotationBeanPostProcessor
),因此<context:annotation-config />
本质上会被忽略。
改变中
BeanFactory factory=new XmlBeanFactory(resource);
至
BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml");
解决了问题。
注释:为了使按名称自动装配策略起作用,在这种情况下,您应该使用驼峰式大小写您的bean名称, address
和person
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.