簡體   English   中英

如何將 RestTemplate 放入單獨的類中?

[英]How to put a RestTemplate into a separate class?

我有一個具有以下RestTemplate定義的 Spring 應用程序:

@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 {
    [...]
  }

[...]

}

我想把getRestTemplate2放到一個單獨的類中。 所以我創建了以下類:

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

}

當我啟動應用程序時,我收到錯誤消息

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.

如何確保創建restTemplate2的代碼位於單獨的類中並被 Spring 正確檢測到?

更新 1:GetRestTemplate2類重命名為GetRestTemplate2Config沒有幫助。

這似乎有效:

@Configuration
@ComponentScan
public class GetRestTemplate2Config {

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM