当我使用像这样的BeanFactory从spring bean配置文件访问bean时:
public class Person {
private String id,address;
@Autowired
private Customer customer;
//setters & getters
}
和bean配置文件
<bean name="person" class="com.ram.spring.model.Person"></bean>
<bean class="com.ram.spring.model.Customer">
<property name="email" value="ram@adp.com"></property>
<property name="name" value="Ram"></property>
</bean>
这里是执行者类
public class PersonExecutor {
public static void main(String[] args) {
BeanFactory context = new XmlBeanFactory(new ClassPathResource("Spring.xml"));
Person person = (Person)context.getBean("person");
System.out.println(person.getCustomer());
}
}
当我执行此操作时,我得到null
。注释不支持BeanFactory吗?任何想法??
答案 0 :(得分:3)
方法1:在xml中包含以下代码
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<!-- Remaining bean declaration -->
</beans>
方法2:删除@Autowired
并仅在xml文件中注入客户。
<bean name="person" class="com.ram.spring.model.Person">
<property name="customer" ref="customer"></property>
</bean>
<bean name="customer" class="com.ram.spring.model.Customer">
<property name="email" value="ram@adp.com"></property>
<property name="name" value="Ram"></property>
</bean>
答案 1 :(得分:1)
您必须使用AnnotationConfigApplicationContext
或
你必须添加到yor Spring.xml来激活注释扫描。
答案 2 :(得分:0)
正如@jens建议的那样
你应该激活annotation scan
<context:component-scan base-package="package_path">
</context:component-scan>
<context:annotation-config />
希望有所帮助