spring mvc中的@propertysource

来源:互联网 发布:minitool数据恢复工具 编辑:程序博客网 时间:2024/05/18 22:16
在spring mvc中,在配置文件中的东西,可以在java代码中通过注解进行读取了: 

@PropertySource  在spring 3.1中开始引入 

比如有配置文件 
config.properties 

mongodb.url=1.2.3.4 
mongodb.db=hello 

则代码中 

@PropertySource("classpath:config.properties")public class AppConfigMongoDB { //1.2.3.4@Value("${mongodb.url}")private String mongodbUrl; //hello@Value("${mongodb.db}")private String defaultDb;@Beanpublic static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {return new PropertySourcesPlaceholderConfigurer();}

则mongodbUrl已经是读取出1.2.3.4的值了,而spring提倡用env去读取值 

@Autowiredprivate Environment env;String mongodbUrl = env.getProperty("mongodb.url");String defaultDb = env.getProperty("mongodb.db");

 要注意的是,要使用 
  
@Bean 
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { 
return new PropertySourcesPlaceholderConfigurer(); 


才能让spring正确解析出${} 中的值 

在spring 3.2中,允许支持多个properties了, 

@Configuration@PropertySource({"classpath:config.properties","classpath:db.properties" //如果是相同的key,则最后一个起作用})public class AppConfig {@AutowiredEnvironment env;}

spring 4.1中,支持@PropertySources 

@Configuration@PropertySources({@PropertySource("classpath:config.properties"),@PropertySource("classpath:db.properties")})public class AppConfig {//...}

在spring 4.2中, 

</pre><pre name="code" class="java">@Configuration@PropertySource("classpath:missing.properties")public class AppConfig {//...}


如果发现missing.properties不存在,则抛出异常 
,也可以使用ignoreResourceNotFound=true去忽略 

@Configuration @PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true) public class AppConfig { //... } 


0 0