绑定@Autowired不工作内部实例启动与'新' [英] Binding with @Autowired not working inside instances initiated with 'new'
本文介绍了绑定@Autowired不工作内部实例启动与'新'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的web spring应用程序中,我创建了一个关键字 new
的实例,如下所示。
在我的一个action类中,存在以下方法。
In my web spring application I create an instance with key word new
as following.
In my one of action class, following method exists.
public void process(){
MyBean b=new MyBean();//initiated the instance with new
b.process();
}
其他MyBean类
@Service
public class MyBean{
@Autowired
MyService service;
public void process(){
service.execute(); // this service instance has not initialized by Spring DI :( .service object is null.
}
}
MyService实例不是通过spring依赖注入来设置的,是因为我自己创建了MyBean的实例,其中新的
不春天?
the MyService instance is not set by spring Dependancy injection. Is it because that I create the instance of MyBean myself with new
not the Spring ?
推荐答案
如果你想以编程方式自动连线,可以使用:
If you want to autowire programmatically, you can use:
private @Autowired AutowireCapableBeanFactory beanFactory;
public void process() {
MyBean obj = new MyBean();
beanFactory.autowireBean(obj);
// obj will now have its dependencies autowired.
}
这篇关于绑定@Autowired不工作内部实例启动与'新'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文