【发布时间】:2018-02-05 14:55:19
【问题描述】:
我有拦截 RestTemplate 的逻辑,我在配置文件中添加/注册 RestTemplate (SecurityConfiguration.java) 但我想通过获取已注册的 RestTemplate 对象从另一个配置文件添加该拦截器:
public class TranslogRestTemplateCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
boolean isRestTemplate = false;
try {
if (context.getBeanFactory() != null) {
isRestTemplate = (context.getBeanFactory().getBean(RestTemplate.class) != null);
}
} catch (BeansException e) {
return false;
}
return isRestTemplate;
}
}
配置类:
@Configuration
public class RestTemplateConfig {
private final MyInterceptor myInterceptor;
@Value("${com.pqr.you.rest.enabled:true}")
private boolean transEnabled;
@Autowired
public RestTemplateConfig(MyInterceptor myInterceptor) {
this.myInterceptor = myInterceptor;
}
@Autowired
private ApplicationContext appContext;
// The logic added below is not working for me
@Bean
@Conditional(TranslogRestTemplateCondition.class)
public RestTemplate addInterceptor(ApplicationContext appContext) {
RestTemplate restTemplate = appContext.getBean(RestTemplate.class);
if (transEnabled) {
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
interceptors.add(myInterceptor);
restTemplate.setInterceptors(interceptors);
}
return restTemplate;
}
}
RestTemplate 的实际逻辑,它将返回所需的拦截器和一些其他值(在返回这个 restTemplate 时,我的拦截器也需要在这里添加,而不是覆盖现有值) 或者 通过获取以下 restTempalte 对象并将 MyInterceptor 添加到 restTemplate。
@Configuration
public class SecurityConfiguration {
@Bean
public AbcInterceptor abcRequestInterceptor(XyzService xyzService) {
return new AbcInterceptor("abc-app", null, xyzService);
}
// I dont want to create bean here
/*@Bean
public MyInterceptor myInterceptor() {
return new MyInterceptor();
}*/
@Bean
public RestTemplate restTemplate(AbcRequestInterceptor abcRequestInterceptor) {
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(abcRequestInterceptor);
//interceptors.add(myInterceptor); // I dont want to add this interceptor here
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
}
【问题讨论】:
-
从
addInterceptor()方法中删除@Conditional注释会发生什么情况? -
添加@Condition 类的原因是,如果我将该 RestTemplateConfig 类移动到其他常见项目,那么我确保目标应用程序应该有 RestTemplate bean 可用
-
好的,但是您确定为您创建了
@Bean(调用了addInterceptor()方法)? -
不,我想调用 addInterceptor()
-
如果有什么想法?????? @gajos
标签: java spring interceptor resttemplate