Load properties file in Spring depending on profile

前端 未结 2 579
一生所求
一生所求 2020-12-17 04:25

I have a Spring 3.1 application. Let\'s say it has an XML with the following content:



        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 04:37

    You can do:

      
    

    It works fine, but is perhaps not adapted when using multiple profiles in the same time.


    When declaring 2 property placeholders, if the 1st one does not contain all the applications keys, you should put the attribute ignoring unresolvable = true, so that the 2nd placeholder can be used. I'm not sure if it is what you want to do, it may if you want both xx1 and xx2 profiles be active in the same time.

    Note that declaring 2 propertyplaceholders like that make them independant, and in the declaration of xx2.properties, you can't reuse the values of xx1.properties.


    If you need something more advanced, you can register your PropertySources on application startup.

    web.xml

      
        contextInitializerClasses
        com.xxx.core.spring.properties.PropertySourcesApplicationContextInitializer
      
    

    file you create:

    public class PropertySourcesApplicationContextInitializer implements ApplicationContextInitializer {
    
      private static final Logger LOGGER = LoggerFactory.getLogger(PropertySourcesApplicationContextInitializer.class);
    
      @Override
      public void initialize(ConfigurableApplicationContext applicationContext) {
        LOGGER.info("Adding some additional property sources");
        String profile = System.getProperty("spring.profiles.active");
        // ... Add property sources according to selected spring profile 
        // (note there already are some property sources registered, system properties etc)
        applicationContext.getEnvironment().getPropertySources().addLast(myPropertySource);
      }
    
    }
    

    Once you've done it you just need to add in your context:

    
    

    Imho it's the best way to deal with spring properties, because you do not declare local properties everywhere anymore, you have a programmatic control of what is happening, and property source xx1 values can be used in xx2.properties.


    At work we are using it and it works nicely. We register 3 additional property sources: - Infrastructure: provided by Puppet - Profile: a different property loaded according to the profile. - Common: contains values as default, when all profiles share the same value etc...

提交回复
热议问题