当尝试使用2.0.3
命令启动Spring Boot mvn clean spring-boot:run
应用程序时,出现以下错误:
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
注释注释的类,那么集成测试也将失败。
如果我从@SpringBootApplication
类中删除了Application
批注,则集成测试运行良好。
答案 0 :(得分:0)
我可以通过创建专用于测试的配置来解决此问题:
@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 TestConfiguration {
}
具有专用于生产的以下配置:
@EnvProd
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Component
@ComponentScan(nameGenerator = PackageBeanNameGenerator.class, basePackages = { "com.thalasoft.user.rest.properties", "com.thalasoft.user.rest.config",
"com.thalasoft.user.rest.service", "com.thalasoft.user.rest.bootstrap", "com.thalasoft.user.data" })
public class ApplicationConfiguration {
}
请注意自定义@EnvProd
注释,该注释可防止测试看到此类。