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

标签 java spring spring-boot reflection

我正在创建 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/

相关文章:

java - 销毁java对象

java - 混淆 Java Web 应用程序

java - IOS 收据验证 IllegalArgumentException

java - 匿名覆盖 HashSet hashCode

java - ResponseEntityExceptionHandler 为 401 异常返回空响应主体

spring - 手动加载应用程序上下文以在 Spring Boot 应用程序中编写 getBean()

java - 运行spring boot application error : Cannot instantiate interface org. springframework.context.ApplicationListener

java - PUT 在 Spring Data Rest 中的 ManyToMany 关联上

java - Spring Boot 集成测试 - 在应用程序上下文启动之前模拟 @Service?

spring - 如何在调用构造函数之前注入(inject) spring @Value 注释值?