Spring注解疑问,谢谢,@Autowired 注释private List<a> as;就自动绑定到a所有的实现类到List没有,谢谢
下面代码无法依赖注入实际的类,请各位大神能否帮忙看看,谢谢,测试代码如下:
public interface HelloBeanInf {
public void test();
}
然后两个实现类
@Service
public class HelloBean implements HelloBeanInf{
private String helloWord = "ssss";
public void test(){
System.out.println(helloWord);
}
}
@Service
public class HelloBean1 implements HelloBeanInf{
private String helloWord = "aaaaa";
public void test(){
System.out.println(helloWord);
}
}
配置文件
bean.xml
<context:annotation-config/>
主类进行调用的
public class SpringTest {
private HelloBeanInf helloBean;
@Autowired
private HelloBeanInf[] helloBeanInfs;//List<HelloBeanInf> helloBeanInfs;
public HelloBeanInf[] getHelloBeanInfs() {
return helloBeanInfs;
}
public void setHelloBeanInfs(HelloBeanInf[] helloBeanInfs) {
this.helloBeanInfs = helloBeanInfs;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
org.springframework.core.io.Resource res = new ClassPathResource("com/cec/bean.xml");
BeanFactory factory = new XmlBeanFactory(res);
SpringTest springTest = new SpringTest();
for (HelloBeanInf t : springTest.getHelloBeanInfs()) {
((HelloBeanInf) t).test();
}
}
报null,依赖没有注入,请问是什么原因没有注入呢,谢谢
------解决方案-------------------- 解决办法:
第一步
@service("springTest")
public class SpringTest {
第二步:
ApplicationContext res = new FileSystemXmlApplicationContext(
"com/cec/bean.xml");
Test springTest = (Test) res.getBean("springTest")
for (HelloBeanInf t : springTest.getHelloBeanInfs()) {
((HelloBeanInf) t).test();
}