1

我正在使用 spring spring security oAuth2 客户端。还有默认的 OAuth2RestTemplate 声明,看起来像

@Bean
@Primary
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext,
        OAuth2ProtectedResourceDetails details) {
    OAuth2RestTemplate template = new OAuth2RestTemplate(details,
            oauth2ClientContext);
    return template;
}

我需要的是提供自定义错误处理,所以我试图把它放到上下文中

@Bean
public OAuth2RestTemplate restTemplate(OAuth2ClientContext oauth2ClientContext,     
         OAuth2ProtectedResourceDetails details) {
    OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(details, oauth2Context);

    restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
        @Override
        public void handleError(ClientHttpResponse response) throws IOException {
            // do some stuff
        }
    });

    return restTemplate;
}

这里的问题是默认实现被注释为@Primary,所以我想知道如何覆盖它?

4

1 回答 1

1

而不是覆盖默认实现,您可能只需获取它的默认实例并设置您需要的所有属性。请参见下面的示例。

@Configuration
public class OverridenConfiguration {
    @Autowire
    private OAuth2RestTemplate restTemplate;

    @PostConstruct
    public void customSettings() {
        System.out.println("************** custom settings ***********");
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                // do some stuff
            }
        });
    }
}
于 2016-03-30T13:45:55.690 回答