Déb*_*ora 3 spring dependency-injection
在我的Web spring应用程序中,我使用关键字创建一个实例,new 如下所示.
在我的一个动作类中,存在以下方法.
public void process() {
MyBean b=new MyBean(); //initiated the instance with new
b.process();
}
Run Code Online (Sandbox Code Playgroud)
其他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.
}
Run Code Online (Sandbox Code Playgroud)
Spring依赖注入不设置MyService实例.是因为我自己创建了MyBean的实例而new不是Spring吗?
如果要以编程方式自动装配,可以使用:
private @Autowired AutowireCapableBeanFactory beanFactory;
public void process() {
MyBean obj = new MyBean();
beanFactory.autowireBean(obj);
// obj will now have its dependencies autowired.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10337 次 |
| 最近记录: |