Spring @PropertySource示例

弹簧属性示例

在Spring中,您可以使用@PropertySource批注将您的配置外部@PropertySource属性文件。 在本教程中,我们将向您展示如何使用@PropertySource读取属性文件并使用@ValueEnvironment显示值。

PS @PropertySource从Spring 3.1开始可用

1. @PropertySource和@Value

一个经典示例,读取属性文件并显示${}

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();
	}

}

注意
要在@Values解析$ {},必须在XML或注释配置文件中注册静态PropertySourcesPlaceholderConfigurer

2. @PropertySource和环境

Spring建议使用Environment获取属性值。

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.更多@PropertySource示例

比较常见的例子。

3.1解决@PropertySource资源位置中的$ {}的示例。

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

在启动期间设置系统属性。

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

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

3.2包括多个属性文件。

@Configuration
	@PropertySource({
		"classpath:config.properties",
		"classpath:db.properties" //if same key, this will 'win'
	})
	public class AppConfig {
		@Autowired
		Environment env;
	}

注意
如果属性键重复,则最后声明的文件将“获胜”并覆盖。

4. Spring 4和@PropertySources

Spring 4的一些增强功能。

4.1引入了新的@PropertySources以支持Java 8和更好的方式来包含多个属性文件。

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

4.2允许@PropertySource忽略未找到的属性文件。

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

如果找不到missing.properties ,则系统无法启动并抛出FileNotFoundException

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

在Spring 4中,您可以使用ignoreResourceNotFound忽略未找到的属性文件

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

做完了

参考文献

  1. Sprong IO – PropertySource
  2. SpringIO – PropertySources
  3. Spring IO –配置
  4. Spring @Value默认值
  5. SpringJIRA:SPR-8539

翻译自: https://mkyong.com/spring/spring-propertysources-example/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值