在Spring中手动解决依赖关系[启动]

Mod*_*ndi 2 java spring dependency-injection spring-boot

似乎应该没什么大不了的,但是Google和StackOverflow似乎都与Spring文档一样不合作(或者我只是不知道在哪里看)。

我的Spring Boot应用程序需要手动实例化某些类。有些类具有依赖关系,所以我不能使用.newInstance(); 相反,我想我需要让Spring从其DI容器中给我该实例。就像是

Class<? extends Interface> className = service.getClassName();
Interface x = SpringDI.getInstance(className);
Run Code Online (Sandbox Code Playgroud)

但是我似乎找不到任何办法。我该怎么办?

编辑

类名是动态解析的,我已经更新了示例pseuido代码以反映这一点。

And*_*ici 5

ApplicationContext在要实例化这些类的组件中自动装配怎么样?在ApplicationContext实现BeanFactory接口时,您可以调用该getBean()方法。

就像是:

@Autowired
private ApplicationContext applicationContext;

[...]

applicationContext.getAutowireCapableBeanFactory().getBean(clazz_name);
Run Code Online (Sandbox Code Playgroud)

我不确定为什么要这样做,因为它违背了使用Spring的目的。(您不能使用Spring,而可以使用Java的反射API)

请参阅JavaDocs的这一部分:http : //docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/BeanFactory.html