gpt4 book ai didi

java - Spring非托管对象的 Autowiring

转载 作者:行者123 更新时间:2023-12-01 09:37:19 25 4
gpt4 key购买 nike

我想知道如何在不受 Spring 应用程序上下文管理的 java 对象中 Autowiring sprig beans。我创建了一个类的实例,但后续的 Autowiring 对象为空。例如。

@Service
Class BaseFactory {
public BaseObject getObject(String type ){
BaseObject object = null;
if(type.equalsIgnoreCase("order")){
object = new FirstServiceObject();
}
else if(type.equalsIgnoreCase("payment")){
object = new SecondServiceObject();
}
return object;
}

服务等级

@Service
@Configurable
public class FirstServiceObject{

@Autowired
UserRepository mUserRepository;// coming as null

@Autowired
UserHelper userHelper;//coming as null

public getDownloadedData(String userName, String b){
User user = userHelper.findUser(userName); //null pointer exception
}

}

我的助手类,我从那里调用上面的内容。

public class SomeHelper {

@Autowired
BaseFactory baseFactory;

public processUser(){
BaseObject object = baseFactory.getObject("order");
object.getDownloadedData("sunil","someString")
}

所有 Autowired beans 在 FirstServiceObject 中都为 null

我已经检查了已经给出的所有可能的解决方案,但似乎没有一个适合我。

最佳答案

以下帖子中给出的答案解决了该问题。 How to inject dependencies into a self-instantiated object in Spring?这就是我所做的

public class SomeHelper {

@Autowired
BaseFactory baseFactory;

@Autowired
AutowireCapableBeanFactory beanFactory;

public processUser(){
BaseObject object = baseFactory.getObject("order");
beanFactory.autowireBean(object);
object.getDownloadedData("sunil","someString");
}
}

关于java - Spring非托管对象的 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38767948/

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