spring 静态变量方式加载properties 文件(支持profile)

发布时间 2023-07-13 18:07:44作者: zno2

 

foo-test.properties (测试环境)

foo-pro.properties (生产环境)

需要根据spring.profiles.active 切换

 

import java.io.IOException;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

@Component
public class FooProperties {


    
    public static String oneProp;
    
    
    @Autowired
    public void setOneProp(@Value("#{foo['one.prop']}") String oneProp) {
        FooProperties.oneProp = oneProp;
    }
    
   
    
    @Bean(name = "foo")
    public Properties getProperties(ApplicationContext ac) {
        Properties properties = new Properties();
        try {
            String path = "foo%s.properties";
            String[] profiles = ac.getEnvironment().getActiveProfiles();
            if (profiles != null && profiles.length > 0 && !"default".equals(profiles[0])) {
                path = String.format(path, "-" + profiles[0]);
            } else {
                path = String.format(path, "");
            }
            properties.load(new ClassPathResource(path).getInputStream());
        } catch (IOException e) {
            throw new RuntimeException("failed for loading file", e);
        }
        return properties;
    }
}

 

这个类有个有意思的地方,@Bean 之后,入参ApplicationContext 可以自动注入,不需要加其他配置;

这里不推荐激活多个profiles ,默认取激活的第一个profile 

比如:

spring: 
  profiles:
    active:
    - test

则会加载 foo-test.properties 中的属性

 

单元测试中激活profiles

@ContextConfiguration(locations = { "classpath:xxx.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@org.springframework.test.context.ActiveProfiles(value="test")
public class FooTest {
...
}