SpringBoot-外部化配置实战应用

 

Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration. Property values can be injected directly into your beans by using the @Valueannotation, accessed through Spring’s Environment abstraction, or be bound to structured objects through @ConfigurationProperties

Spring Boot 允许我们扩展配置信息。通过属性文件、YAML文件,环境变量,命令行参数进行扩展。属性值通过 @Value 注解直接注入到 Spring Bean 中。通过 Spring Environment 这个抽象类进行访问,或者通过@ConfigurationProperties绑定的对象进行访问。

Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values

注意属性值的加载和覆盖。

PropertySource:Abstract base class representing a source of name/value property pairs。

 

Accessing Command Line Properties

// 调整应用的端口为9000
// 犹豫命令行的优先级高于application.properties,所以可以覆盖
java -jar xxx.jar --server.port=9000

// 禁用命令行参数
SpringApplication.setAddCommandLineProperties(false)

Application Property Files

SpringApplication loads properties from application.properties files in the following locations and adds them to the Spring Environment:

1.A /config subdirectory of the current directory
2.The current directory
3.A classpath /config package
4.The classpath root

Spring Boot 加载 application.properites 的顺序 1 > 2 > 3 > 4。

自定义配置文件的文件名和文件路径
java -jar myproject.jar --spring.config.name=myproject
java -jar myproject.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties

Profile-specific Properties

如果没有通过 spring.profiles.active 激活要加载的配置文件,Spring Boot 默认加载appilcation-default.properties

Placeholders in Properties

app.name=MyApp
app.description=${app.name} is a Spring Boot application

Type-safe Configuration Properties

第一步:绑定 key/value
通过使用 ConfigurationProperties 自动绑定 application.proeprteis 中的 key/value 到 AcmeProperties 对象中

第二步:激活
@Configuration
@EnableConfigurationProperties(AcmeProperties.class)
public class MyConfiguration {
}

第三步:
通过 @Autowired 注入 AcmeProperties 即可

注意:复杂类型的绑定也是一样的。

@ConfigurationProperties Validation

@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {

	@NotNull
	private InetAddress remoteAddress;

	@Valid
	private final Security security = new Security();

	// ... getters and setters

	public static class Security {

		@NotEmpty
		public String username;

		// ... getters and setters

	}

}

 @ConfigurationProperties vs. @Value

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值