Spring Environment Property Source Configuration

后端 未结 5 1738
感动是毒
感动是毒 2020-12-28 08:33

I\'m working on an application library with a utility class called \"Config\" which is backed by the Spring Environment object and provides strongl

5条回答
  •  旧巷少年郎
    2020-12-28 08:55

    The following worked for me with Spring 3.2.4 .

    PropertySourcesPlaceholderConfigurer must be registered statically in order to process the placeholders.

    The custom property source is registered in the init method and as the default property sources are already registered, it can itself be parameterized using placeholders.

    JavaConfig class:

    @Configuration
    @PropertySource("classpath:propertiesTest2.properties")
    public class TestConfig {
    
        @Autowired
        private ConfigurableEnvironment env;
    
        @Value("${param:NOVALUE}")
        private String param;
    
        @PostConstruct
        public void init() {
            env.getPropertySources().addFirst(new CustomPropertySource(param));
        }
    
        @Bean
        public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    
        @Bean
        public TestBean1 testBean1() {
            return new TestBean1();
        }
     }
    

    Custom property source:

        public class CustomPropertySource extends PropertySource {
    
        public CustomPropertySource(String param) {
            super("custom");
            System.out.println("Custom property source initialized with param " + param + ".");
        }
    
        @Override
        public Object getProperty(String name) {
            return "IT WORKS";
        }
    
    }
    
    
    

    Test bean (getValue() will output "IT WORKS"):

    public class TestBean1 {
    
       @Value("${value:NOVALUE}")
       private String value;
    
       public String getValue() {
          return value;
       }
    }
    

    提交回复
    热议问题