您的位置:首页 > 其它

关于@Autowired自动注入属性为空

2014-07-27 22:38 375 查看

public class AAAA {

 public Disc getDisc() {

  return disc;

 }

 public void setDisc(Disc disc) {

  this.disc = disc;

 }

 @Autowired

 private Disc disc;

}

public class ProductTest {

 @Test

 public void test(){

  ApplicationContext context = new ClassPathXmlApplicationContext("product-beans.xml");

  AAAA a = (AAAA) context.getBean("aaaa");

  System.out.println(a.getDisc().getName());

 }

 

}

刚开始提示空指针异常,发现是因为a的 disc域没有注入。但是我在spring中已经注入了。如下:

<bean id="disc" class="org.account.product.Disc">

     <property name="name" value="CD-RW"></property>

     <property name="price" value="1.5"></property>

     <property name="capacity" value="700"></property>

    </bean>

<bean id="aaaa" class="org.account.product.AAAA"></bean>

最终解决:需要在spring的配置文件中加入如下代码

<context:component-scan base-package="org.account.product" />

参考:http://blog.csdn.net/chunqiuwei/article/details/16115135
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐