您好,我无法在另一个使用工厂方法实例化的 bean 中自动装配我的 bean。
class A{
private String name;
//getters and setters for name
}
class B{
@Autowired
private A x;
private B(String Gender, String jobProfile){
String name = x.getName();
//some code
}
public static getInstance(String Gender,String jobProfile){
//some code for instantiation.
}
}
现在,当我使用工厂方法从某个不同的类创建类 B 的实例时。自动装配不会发生,它返回 NULL,即 x 为 null。因此,我在调用 getName 时遇到空指针异常
你有什么解决办法吗?或者我做错了什么?
当您通过 new 创建对象时,autowire\inject 不起作用...
作为解决方法,您可以尝试以下操作:
并以这种方式创建一个实例
context.getBean("myBean");
原型:这将单个 bean 定义范围限定为具有任意数量的对象实例。
Config
<bean id="a" class="..." >
<bean id="b" class="..." scope="prototype">
<bean id="factory" class="..." >
工厂类
public class Factory implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
this.applicationContext = applicationContext;
}
public B createClass(){
context.getBean("b");
}
public B createClass(Object... args){
context.getBean("b",args);
}
}
这样自动连线注释就可以正常工作。
正如 Javadocs 所说 getBean ..
/**
* Return an instance, which may be shared or independent, of the specified bean.
* <p>Allows for specifying explicit constructor arguments / factory method arguments,
* overriding the specified default arguments (if any) in the bean definition.
* @param name the name of the bean to retrieve
* @param args arguments to use if creating a prototype using explicit arguments to a
* static factory method. It is invalid to use a non-null args value in any other case.
* @return an instance of the bean
* @throws NoSuchBeanDefinitionException if there is no such bean definition
* @throws BeanDefinitionStoreException if arguments have been given but
* the affected bean isn't a prototype
* @throws BeansException if the bean could not be created
* @since 2.5
*/
Object getBean(String name, Object... args) throws BeansException;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)