【问题标题】:How to put a RestTemplate into a separate class?如何将 RestTemplate 放入单独的类中?
【发布时间】:2021-02-15 02:46:17
【问题描述】:

我有一个 Spring 应用程序,其 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 {
    [...]
  }

[...]

}

我想把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 没有帮助。

【问题讨论】:

  • 只是一个健全的检查,你是否从 MyApplication.java 文件中删除了 bean 定义?
  • @Michal 我删除了第二个,即。 e.在MyApplication 中现在只有getRestTemplate1
  • @4EACH 答案的哪一部分应该有助于解决我的问题?我没有在单独的类中看到任何 bean。
  • 最后一个答案看起来与您相关@Mentiflectax

标签: java spring resttemplate


【解决方案1】:

这似乎有效:

@Configuration
@ComponentScan
public class GetRestTemplate2Config {

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

【讨论】:

  • 你的配置类不需要@ComponentScan注解,除非GetRestTemplate2 在一个完全不同的(非嵌套的)包结构中。
猜你喜欢
  • 1970-01-01
  • 2013-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
  • 2013-01-24
  • 1970-01-01
相关资源
最近更新 更多