我试图将项目迁移到Spring Boot。以前Guice被用作DI。
我们有这样的guice模块
public class RepositoryImplementationModule extends AbstractModule {
@Override
protected void configure() {
new Reflections("com.example").getTypesAnnotatedWith(Repository.class)
.forEach(repositoryClass ->
bind((Class) repositoryClass).toProvider(new RepositoryProvider(repositoryClass)));
}
}
如果您熟悉弹簧数据,这很容易理解。 接口的实现是在app启动时根据某些库的方法名称生成的。
基于此问题How to register multiple beans using single @Bean-annotated method (or similar) in Spring?
我已创建此配置
@Configuration
public class RepositoryImplementationConfig {
@Inject
public RepositoryImplementationConfig(ConfigurableBeanFactory configurableBeanFactory) {
new Reflections("com.example").getTypesAnnotatedWith(Repository.class)
.forEach(repository -> {
configurableBeanFactory.registerSingleton(makeBeanName(repository), generateImplementation(repository));
});
}
private <T extends Class> String makeBeanName(T clazz) {
//just convert class name to spring bean name
return "";
}
private <T extends Class> T generateImplementation(T clazz) {
//make a proxy of class and generate implementation by method names
return clazz;
}
}
我有使用存储库的服务。例如:
@Component
public class MyService {
@Inject
public MyService(AnswerRepository answerRepository) {
System.out.println(answerRepository.findAnswer());
}
}
当我试图运行时,我遇到了错误:
com.example.demo.MyService中构造函数的参数0需要一个类型为&#39; com.example.demo.AnswerRepository&#39;的bean。无法找到。
我将@DependsOn("repositoryImplementationConfig")
添加到MyService - 它可以运行,但我有很多服务,所以这不是解决此问题的便捷方法。
我尝试过使用@Order
,@Prority
,@ConditionalOnMissingBean
,但一无所获。
最后,我想出了这个丑陋的黑客。它有效,但绝对不是正确的做事方式
@SpringBootApplication
public class DemoApplication {
@Inject
RepositoryImplementationConfig repositoryImplementationConfig;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
问题:
RepositoryImplementationConfig
之前初始化MyService
是否有更好的解决方案?