[英]Creating spring bean using BeanFactory.getBean()
Consider there are 2 classes: When creating bean A using factory.getbean(), the bean gets created but the property coldata is null inspite of initializing to new hashmap. 考虑有两个类:使用factory.getbean()创建bean A时,将创建bean,但是属性初始化时为null,尽管初始化为新的hashmap。
@Component
@Scope("prototype")
public class A{
private Map<String, Map<String,String>> coldata = new HashMap<String, Map<String,String>>();
}
@Service
public class B{
@Autowired
private BeanFactory factory;
public void test(){
A a= (A)factory.getBean("A");
System.out.println(a.coldata)
}
}
There's a wrong approach at first to correct. 首先有一个错误的方法来纠正。
First of all, as @Sun says: correct the code and make that map as public or give that field a getter at least. 首先,如@Sun所说:更正代码并使该地图公开,或至少使该字段具有吸气剂。
Secondly If you use autowiring don't use beanFactory: Class A is annotated as Autowired and as a Component. 其次,如果您使用自动装配,请不要使用beanFactory:类A被标注为自动装配和组件。 If you want an instance of that class from the container just use an autowired instance in class B:
如果要从容器中获取该类的实例,只需在B类中使用自动装配的实例:
@Service
public class B{
@Autowired
private A a;
public void test(){
System.out.println(a.coldata)
}
}
avoid using the getBean method of the BeanFactory/ApplicationContext classes, especially if you want to use autowiring. 避免使用BeanFactory / ApplicationContext类的getBean方法,特别是如果要使用自动装配。 Here's a good explanation on why you should avoid using that method: Why is Spring's ApplicationContext.getBean considered bad?
这里有一个很好的解释,说明了为什么应该避免使用该方法: 为什么Spring的ApplicationContext.getBean被认为是错误的?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.