spring以及spring boot参数配置

1.@PropertySource注解

Annotation providing a convenient and declarative mechanism for adding a org.springframework.core.env.PropertySource  to Spring's org.springframework.core.env.Environment . To be used in conjunction with  Configuration classes.

该注解提供了便捷的方式向spring环境中增加PropertySource,该注解需要配合Configuration类使用。

例子1:

app.properties存放在resources目录下,文件内容:

system.name = 系统名称
system.version = 1.0
spring以及spring boot参数配置
@Configuration
@PropertySource(value="classpath:app.properties",name="app-properties")
public class AppConfig {
    
    @Value("${system.name}")
    private String systemName;
    
    @Value("${system.version}")
    private String systemVertion;

    @Autowired
    Environment env;

    @Bean
    public TestBean1 testBean1() {
        TestBean1 testBean1 = new TestBean1();
        testBean1.setName(env.getProperty("testbean.name"));
        return testBean1;
    }
    
    @Bean
    public TestBean2 testBean2() {
        TestBean2 testBean2 = new TestBean2();
        MutablePropertySources propertySources = env.getPropertySources();
        testBean2.setName(propertySources.get("app-properties").getProperty("system.name"));
        return testBean2;
    }
    
}
View Code

 

例子2:

spring以及spring boot参数配置
@Configuration
@PropertySource("classpath:/com/myco/a.properties")
public class ConfigA { }

@Configuration
@PropertySource("classpath:/com/myco/b.properties")
public class ConfigB { }

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(ConfigA.class);
ctx.register(ConfigB.class);
ctx.refresh();
View Code

 

2.@PropertySources注解

Container annotation that aggregates several PropertySource annotations.

这是一个合并多个PropertySource注解的容器注解,它可以减少在有多个配置文件向spring环境中注入的配置。

例如:

@PropertySources({
    @PropertySource(value = {"classpath:a.properties"}, name = "a.properties"), 
    @PropertySource(value = {"classpath:b.properties"}, name = "b.properties")
    })
@Configuration
public class AppConfig {
    
}

 

上一篇:spring PropertySource properties 文件配置


下一篇:那些高曝光的Annotation(@ComponentScan、@PropertySource与@PropertySources、@Import与ImportResource)