【问题标题】:How to inject config settings into autowired spring beans?如何将配置设置注入自动装配的 Spring bean?
【发布时间】:2012-10-25 07:23:00
【问题描述】:

我的项目中有一个用于 web 服务客户端的 bean,它需要注入一些配置设置。我们使用的是 Spring 3.1。目前最好的想法是像这样使用@Value 注释:

@Service
public class MyWebServiceClient {
  private String endpointUrl;

  @Required
  @Value("${mywebserviceClient.endpointUrl}")
  public void setEndpointUrl(String endpointUrl) {
    this.endpointUrl = endpointUrl;
  }

}

但是我不太喜欢将属性名称硬编码到类中。它还存在一个问题,即无法在同一上下文中拥有多个具有不同设置的客户端(因为只有一个属性并且这是硬编码的)。有没有更优雅的方式通过自动装配来做到这一点,还是我应该求助于普通的旧 xml 配置来做到这一点?

【问题讨论】:

    标签: java spring configuration autowired


    【解决方案1】:

    我会使用 JavaConfig 来执行此操作。

    更具体地说,我将使用 JavaConfig 创建多个MyWebServiceClient 实例,并使用正确的端点属性键将配置设置为@Value

    类似这样的:

    @Configuration
    public class MyWebServiceConfig {
        @Required
        @Value("${myWebserviceClient1.endpointUrl")
        private String webservice1Url;
    
        @Required
        @Value("${myWebserviceClient2.endpointUrl")
        private String webservice2Url;
    
        @Required
        @Value("${myWebserviceClient3.endpointUrl")
        private String webservice3Url;
    
        @Bean
        public MyWebServiceClient webserviceClient1() {
            MyWebServiceClient client = createWebServiceClient();
            client.setEndpointUrl(webservice1Url);
            return client;
        }
    
        @Bean
        public MyWebServiceClient webserviceClient2() {
            MyWebServiceClient client = createWebServiceClient();
            client.setEndpointUrl(webservice2Url);
            return client;
        }
    
        @Bean
        public MyWebServiceClient webserviceClient3() {
            MyWebServiceClient client = createWebServiceClient();
            client.setEndpointUrl(webservice3Url);
            return client;
        }
    }
    

    这样,您的ApplicationContext 中应该有3 个MyWebServiceClient 实例,可通过使用@Bean 注释的方法名称获得。

    为了您的方便,这里还有一些documentation to JavaConfig

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多