Spring @PropertySource example

转载 2016年08月29日 13:24:00
spring-properties-example

In Spring, you can use @PropertySource annotation to externalize your configuration to a properties file. In this tutorial, we will show you how to use @PropertySource to read a properties file and display the values with @Value and Environment.

P.S @PropertySource has been available since Spring 3.1

1. @PropertySource and @Value

A classic example, read a properties file and display with ${}.

config.properties
mongodb.url=1.2.3.4
mongodb.db=hello
AppConfigMongoDB
package com.mkyong.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
//...

@Configuration
@ComponentScan(basePackages = { "com.mkyong.*" })
@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 MongoTemplate mongoTemplate() throws Exception {

		MongoClientOptions mongoOptions =
			new MongoClientOptions.Builder().maxWaitTime(1000 * 60 * 5).build();
		MongoClient mongo = new MongoClient(mongodbUrl, mongoOptions);
		MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongo, defaultDb);
		return new MongoTemplate(mongoDbFactory);

	}

	//To resolve ${} in @Value
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
		return new PropertySourcesPlaceholderConfigurer();
	}

}
Note
To resolve ${} in @Values, you must register a static PropertySourcesPlaceholderConfigurer in either XML or annotation configuration file.

2. @PropertySource and Environment

Spring recommends to use Environment to get the property values.

AppConfigMongoDB
package com.mkyong.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
//...

@Configuration
@ComponentScan(basePackages = { "com.mkyong.*" })
@PropertySource("classpath:config.properties")
public class AppConfigMongoDB {

	@Autowired
	private Environment env;

	@Bean
	public MongoTemplate mongoTemplate() throws Exception {

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

		MongoClientOptions mongoOptions =
			new MongoClientOptions.Builder().maxWaitTime(1000 * 60 * 5).build();
		MongoClient mongo = new MongoClient(mongodbUrl, mongoOptions);
		MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongo, defaultDb);
		return new MongoTemplate(mongoDbFactory);

	}

}

3. More @PropertySource Examples

More common examples.

3.1 Example to resolve ${} within @PropertySource resource locations.

@Configuration
@PropertySource("file:${app.home}/app.properties")
public class AppConfig {
	@Autowired
	Environment env;
}

Set a system property during startup.

System.setProperty("app.home", "test");

java -jar -Dapp.home="/home/mkyon/test" example.jar

3.2 Include multiple properties files.

@Configuration
@PropertySource({
	"classpath:config.properties",
	"classpath:db.properties" //if same key, this will 'win'
})
public class AppConfig {
	@Autowired
	Environment env;
}
Note
If a property key is duplicated, the last declared file will ‘win’ and override.

4. Spring 4 and @PropertySources

Some enhancements on Spring 4.

4.1 Introduces new @PropertySources to support Java 8 and better way to include multiple properties files.

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

4.2 Allow @PropertySource to ignore the not found properties file.

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

If missing.properties is not found, the system is unable to start and throws FileNotFoundException

Caused by: java.io.FileNotFoundException:
	class path resource [missiong.properties] cannot be opened because it does not exist

In Spring 4, you can use ignoreResourceNotFound to ignore the not found properties file

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

Done.

springboot源码分析14-ApplicationContextInitializer原理Springboot中PropertySource注解多环境支持以及原理

摘要:Springboot中PropertySource注解的使用一文中,详细讲解了PropertySource注解的使用,通过PropertySource注解去加载指定的资源文件、然后将加载的属性注...
  • qq_30739519
  • qq_30739519
  • 2017年12月14日 11:32
  • 393

Spring @PropertySource example

In Spring, you can use @PropertySource annotation to externalize your configuration to a propertie...
  • daniel7443
  • daniel7443
  • 2016年04月15日 15:19
  • 563

Spring 4 @PropertySource和@Value注解示例

前言 译文链接:http://websystique.com/spring/spring-propertysource-value-annotations-example/ 本篇文章将展示如何通过...
  • yy193728
  • yy193728
  • 2017年03月23日 20:01
  • 2319

spring注解 @PropertySource 配置数据源

一般在配置数据源是都会使用xml的方式注入,key-value在properties中管理;spring4.X已有着比较完善的注解来替换xml的配置方式。...
  • zrk1000
  • zrk1000
  • 2015年07月01日 13:10
  • 10553

spring 源码研究---core包-- PropertySource Environment

/**  * PropertySource 抽象类主要是一对name/value值  * 它对euqals方法进行了重写 主要比较name属性是否相等 用于在集合中比较PropertySource对象...
  • zghwaicsdn
  • zghwaicsdn
  • 2016年03月13日 08:42
  • 1400

spring mvc中的@propertysource

在spring mvc中,在配置文件中的东西,可以在java代码中通过注解进行读取了:  @PropertySource  在spring 3.1中开始引入  比如有配置文件  conf...
  • itchiang
  • itchiang
  • 2016年04月13日 16:03
  • 9590

Spring 使用@PropertySource读取properties文件

spring 3.1中开始引入 了读取properties文件的注解 @PropertySource 比如有customize.properties文件 #超级管理员的用户名 userName=a...
  • u011659172
  • u011659172
  • 2016年04月28日 15:05
  • 14122

spring4.0 @PropertySource读取配置文件

@Configurable @ComponentScan(basePackages = "com.9leg.java.spring") @PropertySource(value = "c...
  • zz210891470
  • zz210891470
  • 2017年04月01日 23:01
  • 2676

【Spring4揭秘 基础2】PropertySource和Enviroment

抽象类PropertySource及子类PropertySource是一个抽象类,它包含一个source和一个name。source可以是map或其他,通常是一组键值对。...
  • u011179993
  • u011179993
  • 2016年05月26日 23:01
  • 5486

spring @PropertySource classpath

Spring @PropertySource 找不到文件的问题,一般是路径没有指引对或者是在classpath:后少加了一个/。 例如正确的姿势是这样的, 而你的可能是这样的...
  • huanglei1234567890
  • huanglei1234567890
  • 2017年05月17日 21:55
  • 511
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Spring @PropertySource example
举报原因:
原因补充:

(最多只允许输入30个字)