java - 在 @Application bean 中使用构造函数注入会导致循环引用
问题描述
我有一个中型弹簧应用程序。当我重构一些 loc 时,我注意到以下行为:
事实上,注射工作正常:
public class AppConfig {
@Autowired
private Environment env;
…
当我尝试使用构造函数注入时,环境为空,我的应用程序告诉我由于循环引用它无法创建我的配置 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;
}
…
在堆栈的某处:
原因:org.springframework.beans.factory.BeanCurrentlyInCreationException:创建名为“appConfig”的bean时出错:当前正在创建请求的bean:是否存在无法解析的循环引用?
我尝试了一些我在网上找到的解决方案,但都没有帮助。我怎样才能正确调试呢?如何找到创建循环引用的位置?
编辑:
编辑2:
可索引服务类:
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:之前,我的环境刚刚为空(这就是该行被删除的原因)。我无法重现空环境,现在我得到循环引用错误。
解决方案
主要问题是由于依赖缺失
通过构造函数参数 0 表示的不满足的依赖关系;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException:在文件 [/Users/ry77/Workspace/Campus/$PROJECT-server/target/$COMPANY.$PROJECT.server-0.0 中定义的名称为“elasticSearch”的 bean 创建错误.1-alpha/WEB-INF/classes/de/$COMPANY/$PROJECT/server/service/searchengine/ElasticSearch.class]:通过构造函数参数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)你的弹性类应该用@Component注解和@autowired注解
希望能帮助到你
推荐阅读
- spring-boot - 尝试多对一实体映射时出现未知列错误
- bison - “轻松”转变/减少冲突
- python-3.x - 读取具有动态值的 sql 文件
- java - 错误:MainActivity.java 上需要类、接口或枚举
- c# - 如何为我的相机设置后期处理图层?
- vscode-settings - 无法在 VSCode 中使用“editor.suggest.showKeywords”禁用语言“关键字”建议:false
- docker - Docker 运行更改密码到 SQL Server 容器
- php - WooCommerce 和 Shippo - Shippo 订单 Obj ID 存储?
- python - 如何将其他文件包含到包中?
- python - 如何将 SWIG 类型图应用于_only_ 特定函数?