以下是我使用ApplicationCOntext
尝试的内容并且工作正常:
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
Employee empl = (Employee)context.getBean("employee");
System.out.println(empl.getName());
我尝试使用XMLBeanFactory同样的事情并没有奏效:
XmlBeanFactory factory = new XmlBeanFactory
(new ClassPathResource("spring-context.xml"));
Employee obj = (Employee) factory.getBean("employee");
System.out.println(obj.getName());
Employee.java
@Component
public class Employee {
@Value(value="XXX")
private String name;
public String getName() {
return name;
}
}
以下是xml文件条目:
<context:component-scan base-package="com.XXX" />
请告知为什么XMLBeanFactory
方法不起作用。
答案 0 :(得分:1)
这是因为XMLBeanFactory只能实例化bean,它会忽略<context:...
个元素。在http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/beans.html#context-introduction-ctx-vs-beanfactory