Search code examples
javarestspring-datamicroservicesspring-cloud-sleuth

spring cloud sleuth and Oauth2Template


We are using microservices with oauth2 as security mechanism. At the moment we are calling other microservices with OAuth2RestTemplate like this:

template.postForObject("http://"+MY_DISCOVERY_NAME+"/path/to/restservice", params, Void.class);

We are using @Autowired to inject OAuth2RestTemplate as follows:

  @Configuration
  public class ApplicationConfig {

      @Autowired
      OAuth2RestTemplate oauth2Resttemplate;
      ...
      @Bean
      public MyBean getMyBean() {
          MyBeanImpl myBean = new MyBeanImpl();
          oauth2Resttemplate.setErrorHandler(getErrorHandler());
          myBean.setTemplate(oauth2Resttemplate);
          return myBean;
      }
      ...
  }

So next step for us is to make the calls tracable. We want to use spring cloud sleuth.

So I added the dependency as follows:

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-sleuth</artifactId>
    </dependency>

After that Spring is not able to autowire OAuth2RestTemplate anymore:

Caused by: java.lang.IllegalArgumentException: Can not set org.springframework.security.oauth2.client.OAuth2RestTemplate

In org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor an IllegalArgumentException is thrown:

            @Override
            protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
                 ...

                            }
                            if (value != null) {
                                    ReflectionUtils.makeAccessible(field);
                                    field.set(bean, value);
                            }
                    }
                ...

field.set(bean, value); results in following Exception:

java.lang.IllegalArgumentException: Can not set org.springframework.security.oauth2.client.OAuth2RestTemplate field my.package.ApplicationConfig.oauth2Resttemplate to com.sun.proxy.$Proxy120

How can I use OAuth2RestTemplate in combination with sleuth?

Thanks

Max


Solution

  • The Problem was that I wired OAuth2RestTemplate instead of interface OAuth2RestOperations.

    Wireing OAuth2RestOperations works for me.