gpt4 book ai didi

java - @Autowired 不能在类实例使用反射创建的类内部工作

转载 作者:行者123 更新时间:2023-11-30 01:54:25 24 4
gpt4 key购买 nike

我正在创建 Spring Boot 应用程序。在此应用程序中,有一组逻辑类,并且此逻辑类实例使用反射创建(基于某些条件逻辑发生变化,这就是我使用反射的原因)在侧面逻辑类中,我尝试自动连接我的存储库类,但它不起作用。该逻辑类使用 @Component 进行注释,但它不起作用。

有什么办法可以做到这一点吗? spring 使用反射来 Autowiring 类,因此我自己使用反射后不知道是否可以使用@Autowired。

代码:

interface ILogic{
void saveUser();
// set of methods
}

@Repository
interface ARepository extends JpaRepository<ARepository,Integer>{}

@Component
class ALogic implement ILogic{
private final ARepository aRepository;
private final BRepository bRepository;
@Autowired
public Alogic(ARepository aRepository, BRepository bRepository){
// code stuff
}
// implementation of methods in ILogic interface
}

@Component
class BLogic implement ILogic{
private final ARepository aRepository;
private final BRepository bRepository;
@Autowired
public Alogic(ARepository aRepository, BRepository bRepository){
// code stuff
}
// implementation of methods in ILogic interface
}

class CreateConstructor{
public ILogic getLogicInstance(){
// give logic class instance base on some condition
}
}

@Service
class userService{

CreateConstructor createConstructor= new CreateConstructor();
public void saveUser(){
createConstructor.getLogicInstance().saveUser();
}
}

存储库类实例不是在逻辑类内部创建的。

编辑:

public ILogic getLogicInstance(String className) {
try {
String packageName = MultiTenantManager.currentTenant.get();// this return required logic class included package name.
Class<?> constructors = Class.forName("lk.example."+packageName+"."+className);
return (ILogic) constructors.getConstructor().newInstance();
} catch () {}
}

最佳答案

Spring 无法在您使用 new 或通过反射创建的实例中注入(inject)任何内容。

执行您想要的操作的方法之一是从应用程序上下文请求 bean,如下所示:


@Autowired
private ApplicationContext applicationContext;

public void createUser(Class<?> beanClass) {
ILogic logic = applicationContext.getBean(beanClass);
logic.saveUser();
}

关于java - @Autowired 不能在类实例使用反射创建的类内部工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959510/

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