我有一个中型 Spring 应用程序。当我重构一些 loc 时,我注意到以下行为:
事实上,注入(inject)工作正常:
public class AppConfig {
@Autowired
private Environment env;
…
当我尝试使用构造函数注入(inject)时,环境为 null 我的应用程序告诉我,由于循环引用,它无法创建我的配置 bean:
public class AppConfig {
private final Environment env;
private final IndexableService indexableService;
@Autowired
public AppConfig(Environment env, IndexableService indexableService) {
this.env = env;
this.indexableService = indexableService;
}
…
堆栈中的某个位置:
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'appConfig': Requested bean is currently in creation: Is there an unresolvable circular reference?
我尝试了一些在网上找到的解决方案,但没有任何帮助。我怎样才能正确调试这个?如何找到循环引用的创建位置?
<小时/>编辑:
<小时/>编辑2:
IndexableService 类:
package de.xx.yy.server.service;
import de.xx.yy.server.model.Indexable;
import java.util.List;
public interface IndexableService {
List<Indexable> search(String searchString);
}
该类的实现:
package de.xxx.yyy.server.service;
import de.xxx.yyy.server.model.Indexable;
import io.leangen.graphql.annotations.GraphQLArgument;
import io.leangen.graphql.annotations.GraphQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class IndexableServiceImpl implements IndexableService {
private final Searcher searcher;
@Autowired
public IndexableServiceImpl(Searcher searcher) {
this.searcher = searcher;
}
@GraphQLQuery(name = "search")
public List<Indexable> search(@GraphQLArgument(name = "searchString") String searchString) {
return searcher.search(searchString);
}
}
PS:之前,我的环境刚刚为空(这就是该行被删除的原因)。我无法重现空环境,现在出现循环引用错误。
最佳答案
主要问题是由于缺少依赖项
Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticSearch' defined in file [/Users/ry77/Workspace/Campus/$PROJECT-server/target/$COMPANY.$PROJECT.server-0.0.1-alpha/WEB-INF/classes/de/$COMPANY/$PROJECT/server/service/searchengine/ElasticSearch.class]: Unsatisfied dependency expressed through constructor parameter 0;
1)@EnableAutoConfiguration 或 @SpringBootApplication 应该出现在主类中
2)确保你的pom中有依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
or
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency
3)您的 Elastic 类应使用 @Component 进行注释,并使用 @autowired 进行注入(inject)
希望对你有帮助
关于java - 在 @Application bean 中使用构造函数注入(inject)会导致循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57427719/