Search code examples
javaspringresttemplate

How to put a RestTemplate into a separate class?


I have a Spring application with the following definition of RestTemplate:

@SpringBootApplication(scanBasePackages = {"com.mycompany"})
public class MyApplication extends SpringBootServletInitializer {

[...]
  @Bean
  public RestTemplate getRestTemplate1() {
    return new RestTemplate();
  }

  @Bean("restTemplate2")
  public RestTemplate getRestTemplate2() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    [...]
  }

[...]

}

I want to put getRestTemplate2 into a separate class. So I created the following class:

@Configuration
@ComponentScan
public class GetRestTemplate2 {
    @Bean("restTemplate2")
    public RestTemplate getRestTemplate2() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
      [...]
    }

}

When I start the application I get the error message

org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'restTemplate2' 
defined in class path resource [XXXXXXXX.class]: Cannot register bean definition 
[Root bean: class [null]; scope=; abstract=false; lazyInit=null; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; 
factoryBeanName=restTemplate2; factoryMethodName=getRestTemplate2; initMethodName=null; destroyMethodName=(inferred); defined 
in class path resource [XXXXXXXXX.class]] for bean 'restTemplate2': 
There is already [Generic bean: class [XXXXXXXXX]; scope=singleton; abstract=false; 
lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; 
initMethodName=null; destroyMethodName=null; defined in file 
[XXXXXXXX.class]] bound.

How can I make sure that the code creating restTemplate2 is located in a separate class and properly detected by Spring?

Update 1: Renaming GetRestTemplate2 class to GetRestTemplate2Config did not help.


Solution

  • This seems to work:

    @Configuration
    @ComponentScan
    public class GetRestTemplate2Config {
    
        @Bean(name = "restTemplate2")
        public RestTemplate getRestTemplate2() throws KeyStoreException, 
            NoSuchAlgorithmException, KeyManagementException {
           [...]
        }
    }