【发布时间】:2018-06-18 02:25:51
【问题描述】:
如何根据 application.yml 文件动态定义 bean?
例如,YAML 文件如下所示:
service:
host: http://localhost:8080/
account:
url: /account
content-type: application/json
registry:
url: /registry
content-type: application/xml
这将动态创建两个带有Content-Type 标头集的HttpHeaders。
我现在是这样定义 bean 的:
@Bean
public HttpHeaders accountHeaders(
@Value("${service.account.content-type}") String contentType
) {
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CONTENT_TYPE, contentType);
return headers;
}
@Bean
public HttpHeaders registryHeaders(
@Value("${service.registry.content-type}") String contentType
) {
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CONTENT_TYPE, contentType);
return headers;
}
如果我需要添加更多端点,我需要复制和粘贴这些 bean,我希望避免这样做。
注意:这些动态 bean 不需要任何其他 bean。我不确定这是否会有所不同。它只需要加载配置。
【问题讨论】:
-
我认为您必须考虑编写可配置的拦截器或过滤器来返回这些标头
-
我不认为可以在这里应用过滤器,因为这些过滤器适用于使用 restTemplate 的外部请求。我从来没有使用过拦截器。有参考吗?
标签: spring spring-boot