【发布时间】:2019-04-17 12:26:36
【问题描述】:
我有 TopicGenerator 接口:
public interface TopicGenerator {
File create(MultiValueMap params);
boolean accept(MultiValueMap params);
}
还有 3 个实现:
@RequiredArgsConstructor
public class JavaTopicGenerator implements TopicGenerator {
//implementation ommited for readability
@RequiredArgsConstructor
public class PhpTopicGenerator implements TopicGenerator {
//implementation ommited for readability
@RequiredArgsConstructor
public class CppTopicGenerator implements TopicGenerator {
//implementation ommited for readability
现在我尝试做的是根据我的参数使用它们,这就是我创建特殊 TopicFacade 的原因。
@RequiredArgsConstructor
public class TopicFacade {
@NonNull
private final TopicService topicService;
@NonNull
private final List<TopicGenerator> topicGenerators;
public void generate(MultiValueMap<String, String> params, HttpServletResponse response) {
for (TopicGenerator topicGenerator : topicGenerators) {
if (topicGenerator.accept(params)) {
File tempFile = topicService.generate(params);
//do something else.
}
}
}
}
在我的 TopicServiceImpl 上我有什么:
@Service
@RequiredArgsConstructor
public class TopicServiceImpl implements TopicService {
@NonNull
private final List<TopicGenerator> reportGenerators;
public File generate(MultiValueMap params) {
for (TopicGenerator topicGenerator : topicGenerators) {
if (topicGenerator.create(params)) {
return topicGenerator.export(params);
}
}
我收到如下错误:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'topicServiceImpl': Unsatisfied dependency expressed through field 'topicGenerators'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.util.List<com.topic.service.TopicGenerator>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
(早些时候,当我使用字段注入而不是构造函数时,我能够在 3 个实现之一之前添加 @Service,并且代码正在处理该单个实现,但它不是我想要的)
【问题讨论】:
-
CppTopicGenerator等实际上在哪里声明为 beans?我只看课。您需要使用构造型注释它们,或使用@Configuration类。 -
@Michael 我尝试用构造型注释它们(在我尝试服务注释或组件注释的那 3 个类之前),出现错误原因:org.springframework.beans.factory.NoSuchBeanDefinitionException:否TopicFacade 类型的合格 bean 可用:预计至少有 1 个 bean 有资格作为 autowire 候选。依赖注释:{}
-
@degath 如果你想使用依赖注入,你必须用构造型注释 every 类。所以每个
TopicGenerator、Service和Facade都需要一个原型注解 -
@Lino by
every你是说那三个?正确的?然后检查我的最后评论。我这样做了,但出现了错误。我尝试了服务和组件注释。 -
Is there an unresolvable circular reference意味着你有一个类A使用类B和B使用A。如果是这种情况,您将不得不考虑您的应用程序结构
标签: java spring spring-boot dependency-injection