【发布时间】:2018-07-10 14:10:47
【问题描述】:
当尝试使用 mvn clean spring-boot:run 命令启动 Spring Boot 2.0.3 应用程序时,我收到以下错误:
Field applicationProperties in com.thalasoft.user.rest.security.TokenAuthenticationServiceImpl required a single bean, but 2 were found:
- userProdProperties: defined in file [/home/stephane/dev/java/projects/user-rest/target/classes/com/thalasoft/user/rest/config/properties/UserProdProperties.class]
- com.thalasoft.user.rest.config.properties.UserProdProperties: defined in file [/home/stephane/dev/java/projects/user-rest/target/classes/com/thalasoft/user/rest/config/properties/UserProdProperties.class]
但是只有一个这样的UserProdProperties类:
@EnvProd
@Configuration
@PropertySource({ "classpath:user-prod.properties" })
public class UserProdProperties extends AbstractUserProperties {
private static Logger logger = LoggerFactory.getLogger(UserProdProperties.class);
public UserProdProperties() {
logger.debug("Loading the Prod properties file");
}
}
而使用注入 bean 的服务类没有构造函数:
@Service
public class TokenAuthenticationServiceImpl implements TokenAuthenticationService {
@Autowired
private UserProperties applicationProperties;
}
我的应用程序从以下类开始:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
应用程序配置通过类完成:
@Configuration
@EnableAutoConfiguration
@ComponentScan(nameGenerator = PackageBeanNameGenerator.class, basePackages = { "com.thalasoft.user.rest.config",
"com.thalasoft.user.rest.service", "com.thalasoft.user.rest.bootstrap", "com.thalasoft.user.data" })
public class ApplicationConfiguration {
}
并且web配置类使用如下注解:
@EnableAutoConfiguration
@EnableWebMvc
@EnableSpringDataWebSupport
@ComponentScan(nameGenerator = PackageBeanNameGenerator.class, basePackages = { "com.thalasoft.user.rest.exception",
"com.thalasoft.user.rest.controller", "com.thalasoft.user.rest.assembler" })
public class WebConfiguration implements WebMvcConfigurer {
}
更新:我现在注意到,如果存在具有 @SpringBootApplication 注释的类,则集成测试会失败。
@SpringBootApplication 注释有一些东西。
如果我有一个用@SpringBootApplication 注释注释的类,那么集成测试也会失败。
如果我从Application 类中删除@SpringBootApplication 注释,那么集成测试运行良好。
【问题讨论】:
-
我怀疑它被注册了两次,因为它被
@Configuration注释并且还在其他地方被@EnableConfigurationProperties引用。我无法确定,因为您没有共享足够的代码。 -
我没有明确使用
@EnableConfigurationProperties注释。它不在我的代码库中。但也许@SpringBootApplicationannoation 正在使用它或类似的东西,我仅使用它来在生产模式下启动应用程序。如果我从UserProdProperties类中删除@Configuration注释,那么我在逻辑上会得到一个未找到属性的错误,因为没有加载属性bean。我还应该分享代码库中的哪些内容? -
您应该分享重现问题所需的最低限度。详情请见stackoverflow.com/help/mcve。
-
另外,
UserProdProperties不是配置类。配置类用于定义 bean,通常具有一个或多个@Bean方法。它应该用@Component而不是@Configuration注解。 -
我将这些属性类中的所有
@Configuration注释替换为@Component注释。但错误仍然相同。
标签: spring-boot