关于spring的BeanFactory在使用注解的注解事项

来源:互联网 发布:淘宝客服美女头像 编辑:程序博客网 时间:2024/06/05 07:30

今天在学习spring的时候,初始化BeanFactory的方法是:

BeanFactory bf=new XmlBeanFactory(new ClassPathResource("bean.xml"));

然后使用bf来初始化带有注解的bean,发现注解无法正常读取。例子如下:

<span style="font-size:14px;">public static void main(String[] args) {BeanFactory bf=new XmlBeanFactory(new ClassPathResource("bean.xml"));//BeanFactory bf=new ClassPathXmlApplicationContext("bean.xml");TestAnnotation ann=(TestAnnotation)bf.getBean("annotation");//注解方式实例化AppSystem.out.println(ann.getApp());}</span>
TestAnnotation:

<span style="font-size:14px;">public class TestAnnotation {@Resource(name="app")private App app;public App getApp() {return app;}public void setApp(App app) {this.app = app;}}</span>


bean.xml:

<span style="font-size:14px;"><bean id="app" scope="prototype" class="org.fucture.core.App"></bean><bean id="annotation" class="org.fucture.core.TestAnnotation"></bean></span>


经过查找所有环境搭建都是正确的,最后发现使用new XmlBeanFactory(new ClassPathResource("bean.xml"));实例化出来的对象是
无法读取spring注解配置文件的,因此修改成
new ClassPathXmlApplicationContext("bean.xml");就成功了。



0 0