我有一个令人费解的 Spring 季错误信息,好吧,多年来我有一些,但这一个是要记住的 .
错误消息是:
Field orderService in com.thalasoft.butik.rest.config.FixtureService required a single bean, but 2 were found:
- com.thalasoft.butik.data.service.OrderServiceImpl: defined in URL [jar:file:/home/stephane/.m2/repository/com/thalasoft/butik-data/0.0.1-SNAPSHOT/butik-data-0.0.1-SNAPSHOT.jar!/com/thalasoft/butik/data/service/OrderServiceImpl.class]
- OrderService: defined by method 'OrderService' in class path resource [com/thalasoft/butik/data/config/JpaService.class]
butik
应用程序由2个Spring项目组成,一个是 butik-data
项目,另一个是 butik-rest
项目 .
在 butik-rest
项目中运行集成测试时发生错误
mvn clean install -Denv="test" -Ddb="h2"
运行应用程序而不运行集成测试时会发生同样的错误:
mvn clean spring-boot:run
依赖关系仅在 pom.xml
文件中出现一次:
<dependency>
<groupId>com.thalasoft</groupId>
<artifactId>butik-data</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
我的 butik-rest
项目配置如下:
@EnvProd
@SpringBootApplication
@Slf4j
public class Application implements CommandLineRunner {
@Component
@ComponentScan(nameGenerator = PackageBeanNameGenerator.class, basePackages = { "com.thalasoft.butik.rest.service", "com.thalasoft.butik.data" })
public class ApplicationConfiguration {
}
@Component
@EnableWebMvc
@EnableSpringDataWebSupport
@ComponentScan(nameGenerator = PackageBeanNameGenerator.class, basePackages = { "com.thalasoft.butik.rest.exception",
"com.thalasoft.butik.rest.controller", "com.thalasoft.butik.rest.assembler" })
public class WebConfiguration implements WebMvcConfigurer {
集成测试配置:
@RunWith(SpringRunner.class)
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = {
"classpath:mysql/clean-up-before-each-test.sql" })
public abstract class BaseTest {
@Configuration
@EnableAutoConfiguration
@ComponentScan(nameGenerator = PackageBeanNameGenerator.class, basePackages = { "com.thalasoft.butik.rest.config",
"com.thalasoft.butik.rest.service", "com.thalasoft.butik.data" })
public class TestConfiguration {
}
@EnableWebSecurity
@ComponentScan(nameGenerator = PackageBeanNameGenerator.class, basePackages = { "com.thalasoft.butik.rest.filter" })
public class NoSecurityConfiguration extends WebSecurityConfigurerAdapter {
服务bean在依赖项目中显式实例化:
@Configuration
public class JpaService {
@Bean
public ProductServiceImpl ProductService() {
return new ProductServiceImpl();
}
@Bean
public OrderServiceImpl OrderService() {
return new OrderServiceImpl();
}
}
可能是Spring从 butik-data
项目中的显式实例化获取一个bean,而另一个来自依赖 butik-rest
项目中的 "com.thalasoft.butik.data"
扫描?
更新:即使将 "com.thalasoft.butik.data"
的两个实例(有一个运行应用程序而另一个运行集成测试)更改为 "com.thalasoft.butik.data.config"
,我仍然会得到相同的错误 .
更新:我看到我有2个错误,使整个问题变得有点棘手 . 我还必须从集成测试中删除 "com.thalasoft.butik.data.config"
实例 . 而现在问题已经消失 .
1 回答
您似乎已经扫描了这两个位置 . 您需要调查当前扫描的位置以及应扫描的位置 .
如果您认为当前的扫描方式(包括两个适合自动装配'orderService'字段的bean),您可以通过注释@Primary(docs:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Primary.html)标记其中一个bean .
标记为此注释的Bean将优先于另一个注释,这可以解决您的问题 .
祝好运 :)