gpt4 book ai didi

spring - 与 @Autowired 绑定(bind)在以 'new' 启动的实例内不起作用

转载 作者:行者123 更新时间:2023-12-04 21:57:47 26 4
gpt4 key购买 nike

在我的 web spring 应用程序中,我使用关键字 new 创建了一个实例。如下。
在我的一个 Action 类中,存在以下方法。

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 依赖注入(inject)设置的。是不是因为我自己用 new 创建了 MyBean 的实例?不是 Spring 吗?

最佳答案

如果要以编程方式 Autowiring ,可以使用:

private @Autowired AutowireCapableBeanFactory beanFactory;

public void process() {
MyBean obj = new MyBean();
beanFactory.autowireBean(obj);
// obj will now have its dependencies autowired.
}

关于spring - 与 @Autowired 绑定(bind)在以 'new' 启动的实例内不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25635845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com