使用不同的属性集加载相同的类

时间:2014-10-24 05:42:09

标签: java spring

我正在尝试实现一个场景,我需要在单个JVM中的不同应用程序上下文中加载具有不同属性集的同一个类。

e.g。 (忽略小错误,这只是为了给出一个高层次的想法)

类别:

public class TestMe {
   private String name;

   public void setName(String name) {
      this.name=name;
   }

   public String getName() {
      return name;
   }
}

我的属性文件应该是:

context1.prop.name=Hello
context2.prop.name=World

Bean定义类似于:

<beans>
   <bean id="testMe" class="TestMe">
      <property name="name" value="${prop.name}" />
   </bean>
</beans>

因此,当加载context1时,所有以context1为前缀的属性都将用于构建上下文。

当加载context2时,所有以context2为前缀的属性都将用于构建上下文。

最后,我的应用程序中将包含2个上下文的地图,其中包含具有相同ID的bean。

我使用PropertyPlaceholderConfigurer实现了Spring的配置版本。但我想摆脱xmls并坚持使用注释。任何人都可以建议如何做到这一点。

1 个答案:

答案 0 :(得分:0)

您可以将context1 / context2分隔为两个属性文件,并使用环境变量传递有关使用哪个文件的信息。然后你必须配置PropertySourcesPlaceholderConfigurer,如:

public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
    properties.setLocations(new ClassPathResource[]{
            new ClassPathResource("config/"+System.getenv("env") + ".properties"),
    });

    return properties;
}

所以它将加载例如config / context1.properties文件。您可以在运行app时使用-Denv=context1传递此变量。

第二个解决方案可以使用内置的配置文件和弹簧支持加载特定文件(例如,如果您使用&#39; test&#39;配置文件,它将自动为您加载application-test.properties)

第3名 - yaml支持 - 看看http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

相关问题