spring mvc中的@propertysource

在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;


@Bean
  public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
    return new PropertySourcesPlaceholderConfigurer();
  }

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

@Autowired
  private 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 {
    @Autowired
    Environment env;
  }

spring 4.1中,支持@PropertySources

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

在spring 4.2中,

@Configuration
  @PropertySource("classpath:missing.properties")
  public class AppConfig {
    //...
  }

如果发现missing.properties不存在,则抛出异常

,也可以使用ignoreResourceNotFound=true去忽略

@Configuration

@PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)

public class AppConfig {

//...

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值