zoukankan      html  css  js  c++  java
  • 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 {

    //...

    }

  • 相关阅读:
    【算法】数据结构
    【POJ】1222 EXTENDED LIGHTS OUT
    【BZOJ】1013 [JSOI2008]球形空间产生器sphere
    【有上下界网络流】【ZOJ】2314 Reactor Cooling
    【CODEVS】1281 Xn数列
    【POJ】3070 Fibonacci
    【CODEVS】3546 矩阵链乘法
    【BZOJ】1070: [SCOI2007]修车
    Quoit Design(hdu 1007)
    tree(poj 1741)
  • 原文地址:https://www.cnblogs.com/panxuejun/p/6909769.html
Copyright © 2011-2022 走看看