【问题标题】:How to do following XML config in to Java config如何在 Java 配置中执行以下 XML 配置
【发布时间】:2019-08-15 21:26:35
【问题描述】:

我正在将 XML 配置转换为 Java 配置。我不确定如何执行以下 XML 配置。请帮忙。谢谢

  <beans profile="!cloud">
    <bean name="remotingURL" class="java.lang.String">
        <constructor-arg value="${web.remoting.url.base}/#{applicationID.toLowerCase()}server/remoting" />
    </bean>
</beans>
<beans profile="cloud">
    <bean name="remotingURL" class="java.lang.String">
        <constructor-arg value="${web.remoting.url.base}/remoting" />
    </bean>
</beans>

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    为您需要的每个配置文件创建一个配置类。然后使用 @Value 从您的属性中注入值。

    @Configuration
    @Profile("cloud")
    public class CloudConfig{
    @Bean
    public String remoteURL(@Value("${web.remoting.url.base}") String url) {
    return url + "/remoting";
    }
    }
    
    @Configuration
    @Profile("!cloud")
    public class RemoteConfig{
    @Bean
    public String remoteURL(@Value("${web.remoting.url.base}") String url, String applicationID) {
    return url + "/" + applicationId.toLowerCase() + "server/remoting";
    }
    }
    

    【讨论】:

    • 谢谢,马丁。我用了你的方法。
    【解决方案2】:
    @Configuration
      public class Test {
    
      @Bean(name = "remotingURL")
      @Conditional(NotCloud.class)
      public String remotingURL1(@Value("${web.remoting.url.base}") String url, String applicationID) {
        return new String(url + "/" + applicationId.toLowerCase() + "server/remoting");
      }
    
      @Bean(name = "remotingURL")
      @Conditional(Cloud.class)
      public String remotingURL2(@Value("${web.remoting.url.base}") String url) {
        return new String(url + "/remoting");
      }
    
    
        }        
    
         @Override
         public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
                    return !context.getEnvironment().getActiveProfiles().toString().equalsIgnoreCase("cloud");
                  }
                }
    
    
    
        public class NotCloud implements Condition {
    
          @Override
          public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            return !context.getEnvironment().getActiveProfiles().toString().equalsIgnoreCase("cloud");
          }
        }
    

    【讨论】:

    • 谢谢,Rakesh,使用@Conditional 代替@Profile 有什么好处?
    • Conditional 从 Spring 4.0 开始引入,允许开发人员定义条件检查。示例:我们可以使用配置文件基于环境加载应用程序,条件可以用于操作系统级别(Windows/Linux)或条件 Bean 的方法的注释或基于 Bean 对象的条件存在于 Spring 应用程序上下文中。在这个解决方案中,我已经回答了而不是创建两个配置类(每个配置文件一个),我更喜欢保持代码最少,但同样可以使用@martin-baumgartner 提供的答案来实现。
    猜你喜欢
    • 1970-01-01
    • 2019-11-27
    • 2023-03-21
    • 2016-10-24
    • 2012-10-19
    • 1970-01-01
    • 2015-07-22
    • 2014-10-30
    • 2013-10-24
    相关资源
    最近更新 更多