【问题标题】:Dynamic configuration of a SOAP client anotated with @Bean使用 @Bean 注释的 SOAP 客户端的动态配置
【发布时间】:2020-09-21 06:53:05
【问题描述】:

我的 Spring Boot 应用程序实现了一个 SOAP 客户端,如下所述:

@Configuration
public class MyClientConfiguration {

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        // this package must match the package in the <generatePackage> specified in pom.xml
        marshaller.setContextPath("de.mypackage");
        return marshaller;
    }

    @Bean
    public MyClient myclient(Jaxb2Marshaller marshaller) {
        MyClient client = new MyClient();
        client.setMarshaller(marshaller);
        client.setUnmarshaller(marshaller);
        return client;
    }
}

取决于另一个属性 target 我需要使用不同的 URI 配置这个 MyClient 对象,例如

  • 对于target=1,客户端必须配置为使用setDefaultUri("http://uri-1")
  • 对于target=2,客户端必须配置为使用setDefaultUri("http://uri-2")

我很难理解如何做到这一点。

【问题讨论】:

    标签: spring spring-boot soap-client


    【解决方案1】:

    关于您的第一个问题:

    //这个包必须匹配pom.xml中指定的包 marshaller.setContextPath("de.mypackage");

    您可以使用 maven 资源插件使用 @property.name@ 语法将 maven 属性硬编码到属性或 yaml 文件中。第一步是添加一个自定义属性,并在插件部分引用该属性:

    pom.xml

    <properties>
      <pluginName.generatePackage>de.mypackage</pluginName.generatePackage>
    </properties>
    
    ...
    
    <plugin>
      <groupId>org.plugin</groupId>
      <artifactId>pluginName</artifactId>
      ...
      <configuration>
        <schemaDirectory>${pluginName.generatePackage}</schemaDirectory>
      </configuration>
    </plugin>
    

    然后,在 application.properties(或 yaml 文件)中定义一个新属性并引用 maven 属性:

    application.properties

    pluginName.generatePackage=@pluginName.generatePackage@
    

    application.yaml

    pluginName:
      generatePackage: '@pluginName.generatePackage@'
    

    最后,将属性注入到您的 bean 配置中:

        @Bean
        public Jaxb2Marshaller marshaller(@Value("${pluginName.generatePackage}") String generatePackage) {
            Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
            marshaller.setContextPath(generatePackage);
            return marshaller;
        }
    
    

    如果您使用的是 Spring Boot starter parent,则无需额外配置即可使用上述设置。否则你可能需要添加一些here描述的资源配置。

    关于你的第二个问题:

    根据另一个属性目标,我需要配置这个 MyClient 具有不同 URI 的对象,例如

    一旦您获得了 pom.xml 属性,就有许多选项。如果配置不是那么复杂,可以使用类似的字符串注入和 bean 定义中的一些自定义逻辑来创建 bean,或者使用 conditionalOn* 注释,例如:

    @Bean
    @ConditionalOnProperty(name = "target", havingValue="1")
    public MyClient myclient(Jaxb2Marshaller marshaller) {
      // .. bean 1 definition
    }
    
    @Bean
    @ConditionalOnProperty(name = "target", havingValue="2")
    public MyClient myclient(Jaxb2Marshaller marshaller) {
      // .. bean 2 definition
    }
    

    如果 bean 定义有点复杂,可以考虑设置一个FactoryBean

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多