[英]Spring Boot — why doesn't the @ComponentScan work with my package combination?
[英]Spring boot: @Profile @Bean combination doesn't work
我已经对这两个 bean 进行了编码:
@Bean
public HttpClient httpClient() throws Exception {
LOG.debug("http client for NO PRE");
return HttpClients.custom().build();
}
@Bean
@Profile("pre")
public HttpClient httpClientPre() throws Exception {
LOG.debug("http client for PRE");
//...
HttpClient client = HttpClients.custom().build();
return client;
}
在另一边,我有另一个豆子:
@Bean
@Primary
public RestTemplate restTemplate(RestTemplateBuilder builder, HttpClient httpClient) throws Exception {
return builder.requestFactory(() -> new HttpComponentsClientHttpRequestFactory(httpClient))
.build();
}
如您所知,当"pre"
处于活动状态时,我希望达到httpClientPre
。 但是,尽管活动配置文件是“pre”,但仍未达到。 查看日志:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.4.RELEASE)
13:20:31.746 [main] INFO n.g.t.e.s.SchedulerApplication - Starting SchedulerApplication on psgd with PID 9538 (/home/jeusdi/projects/repositori-digital/rep-digital-scheduler/target/classes started by jeusdi in /home/jeusdi/projects/repositori-digital)
13:20:31.760 [main] DEBUG n.g.t.e.s.SchedulerApplication - Running with Spring Boot v2.0.4.RELEASE, Spring v5.0.8.RELEASE
13:20:31.767 [main] INFO n.g.t.e.s.SchedulerApplication - The following profiles are active: pre <<<<<<<<<<<<
但是,我期待获得"http client for PRE"
日志。 尽管如此,我得到:
13:20:48.613 [main] DEBUG n.g.t.e.s.c.ServicesConfiguration - http client for NO PRE <<<<<<
这意味着尽管当前配置文件是pre
,但仍未达到httpClientPre
。
有任何想法吗?
编辑
我也试过@Profile("!pre")
,但我收到了这条消息:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 1 of method restTemplate in net.gencat.transversal.espaidoc.scheduler.config.ServicesConfiguration required a bean named 'httpClient' that could not be found.
Action:
Consider defining a bean named 'httpClient' in your configuration.
编辑2
我也尝试过:
但它不断收到上面的消息。
看来你应该用@Profile
标记所有@Bean
方法
注意:在@Bean 方法上使用@Profile,可能会出现一种特殊情况:在重载@Bean 方法的情况下,相同的Java 方法名称(类似于构造函数重载),需要在所有重载方法上一致地声明@Profile 条件. 如果条件不一致,则只有重载方法中第一个声明的条件才重要。 因此,@Profile 不能用于 select 一个具有特定参数签名的重载方法; 同一 bean 的所有工厂方法之间的解析在创建时遵循 Spring 的构造函数解析算法。 如果您想定义具有不同配置文件条件的替代 bean,请使用指向相同 bean 名称的不同 Java 方法名称; 请参阅 @Configuration 的 javadoc 中的 ProfileDatabaseConfig。
这里的原因是您正在创建具有 2 个不同名称的 bean(方法名称 == bean 的名称),并且在发生注入时会考虑 bean 的名称 - bean 名称 == 参数名称。
在您的情况下,您正在注入httpClient
但您正在创建httpClient
和httpClientPre
- 因此注入了httpClient
使用@Profile("!pre")
是通往 go 但与@Qualifier
结合使用的方式,因此您可以正确命名 bean,例如。
@Bean
@Profile("!pre")
public HttpClient httpClient() throws Exception
@Bean
@Profile("pre")
@Qualifier("httpClient")
public HttpClient httpClientPre() throws Exception
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.