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.

相关文章推荐

spring注解 @PropertySource 配置数据源

一般在配置数据源是都会使用xml的方式注入,key-value在properties中管理;spring4.X已有着比较完善的注解来替换xml的配置方式。

Spring的@PropertySource和@Value注解例子

Spring的@PropertySource和@Value注解例子 Published: 12 Feb 2015 Category: spring 在这篇文章中,我们会利用Spring的@...

Spring 4 @PropertySource和@Value注解示例

阅读目录 前言涉及的技术及开发工具工程结构目录步骤一:往pom.xml中添加依赖步骤二:创建Spring配置类步骤三:创建配置文件步骤四:创建服务类步骤五:创建Main方法运行程序工程源码 ...

(15)spring boot使用@Value,@PropertySource注解使用

******@Value****** 在spring boot中,有些变量根据需求配置在application.properties中, 在应用程序中使用@Value注解获取值。 eg: ...

Spring AOP + AspectJ annotation example

In this tutorial, we show you how to integrate AspectJ annotation with Spring AOP framework. In simp...

Spring3MVC:Internationlization&Localization Tutorial with Example

我们将会创建两个properties文件,他们包含显示的所有信息,这些文件被放在叫做resources的目录中, Right click on Project name > New > Source...

Spring MVC Display, Validate and Submit Form Example

In any web application, you often have to deal with forms. Application first displays a form and aft...

Spring MVC with ParameterizableViewController Tutorial and Example

dispatcher-servlet.xml ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18...

Spring Security + Hibernate Annotation Example

In this tutorial, previous Spring Security + Hibernate4 XML example will be reused, and convert it t...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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