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

Rid*_*nga 3 java reflection spring spring-boot

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

有什么办法可以做到这一点吗?spring 使用反射来自动装配类,因此我自己使用反射后不知道是否可以使用@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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 () {}
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*nin 5

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

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


@Autowired 
private ApplicationContext applicationContext;

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

Run Code Online (Sandbox Code Playgroud)