Spring的Environment使用

我们先来看看相关的类图:

这里我们看源码提倡将相关的类图都整理出来,一来可以从整体上了解Spring的设计结构,二来可以学习代码设计架构,对自己设计项目架构能力有很大帮助,在这里通常暴露出来给编程人员的接口是Environment,但是我们可以看到具体功能的实现是分为两个大分支的,对外接口往往需要精简,内部实现则需要结构清晰。Environment相关使用分为两部分,一个是Properties属性的使用一个是Profile使用。我们先来看看Properties属性的使用:

引入properties配置文件:

<context:property-placeholder location="classpath:db.properties" />

使用方式:

@Autowired
private Environment environment;

public void getProperty() {
  environment.getProperty("jdbc.driverClassName");
}

类似使用注解的方式如下:

@Configuration
@PropertySource("classpath:db.properties")
public class TestProperties {
	@Autowired
	Environment env;

	public void getProperty() {
		environment.getProperty("jdbc.driverClassName");
	}
}

这是有关Properties的使用,下面来讲profile的使用,profile的使用是为了能以最简单的方式切换配置文件,通常是简化多个环境不同配置的复杂,下面我们来看看使用方式:

<beans profile="test">
	<context:property-placeholder location="/WEB-INF/test.properties" />
</beans>

<beans profile="beta">
	<context:property-placeholder location="/WEB-INF/beta.properties" />
</beans>

激活指定profile的三种方式:

1、代码指定

ConfigurableEnvironment.setActiveProfiles("test")

2、配置文件指定

<init-param>
  <param-name>spring.profiles.active</param-name>
  <param-value>beta</param-value>
</init-param>

3、Tomcat启动参数指定

JAVA_OPTS="-Dspring.profiles.active=test"

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值