环境抽象
Environment
接口是一个集成在容器中的抽象,它建模了应用程序环境的两个关键方面:配置文件 和 属性。配置文件是一个命名的逻辑性 bean 定义组,仅当给定配置文件处于活动状态时才注册到容器中。无论是在 XML 中定义还是使用注解,bean 都可以分配给某个配置文件。Environment
对象与配置文件相关的角色是确定哪些配置文件(如果有)当前处于活动状态,以及哪些配置文件(如果有)应该默认处于活动状态。属性在几乎所有应用程序中都扮演着重要的角色,并且可能来自各种来源:属性文件、JVM 系统属性、系统环境变量、JNDI、servlet 上下文参数、临时 Properties
对象、Map
对象等等。Environment
对象与属性相关的角色是为用户提供一个方便的服务接口,用于配置属性源并从中解析属性。
Bean 定义配置文件
Bean 定义配置文件在核心容器中提供了一种机制,允许在不同的环境中注册不同的 bean。"`环境`"这个词对不同的用户可能意味着不同的事物,此功能可以帮助解决许多用例,包括:
-
在开发中使用内存中的数据源,而在 QA 或生产环境中从 JNDI 查找相同的数据源。
-
仅当将应用程序部署到性能环境时才注册监控基础设施。
-
为客户 A 和客户 B 的部署注册 bean 的定制实现。
考虑实际应用程序中需要 DataSource
的第一个用例。在测试环境中,配置可能类似于以下内容:
-
Java
-
Kotlin
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("my-schema.sql")
.addScript("my-test-data.sql")
.build();
}
@Bean
fun dataSource(): DataSource {
return EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("my-schema.sql")
.addScript("my-test-data.sql")
.build()
}
现在考虑如何将此应用程序部署到 QA 或生产环境,假设应用程序的数据源已注册到生产应用程序服务器的 JNDI 目录中。我们的 dataSource
bean 现在看起来像以下列表:
-
Java
-
Kotlin
@Bean(destroyMethod = "")
public DataSource dataSource() throws Exception {
Context ctx = new InitialContext();
return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
}
@Bean(destroyMethod = "")
fun dataSource(): DataSource {
val ctx = InitialContext()
return ctx.lookup("java:comp/env/jdbc/datasource") as DataSource
}
问题在于如何根据当前环境在这两个变体之间切换。随着时间的推移,Spring 用户设计了许多方法来完成此操作,通常依赖于系统环境变量和 XML <import/>
语句的组合,其中包含 ${placeholder}
令牌,这些令牌根据环境变量的值解析为正确的配置文件路径。Bean 定义配置文件是核心容器功能,它为此问题提供了解决方案。
如果我们概括前面示例中所示的环境特定 bean 定义的用例,我们最终需要将某些 bean 定义注册到某些上下文中,而不是其他上下文中。可以说,您希望在情况 A 中注册某种 bean 定义配置文件,而在情况 B 中注册不同的配置文件。我们首先更新配置以反映此需求。
使用 @Profile
@Profile
注解允许您指示当一个或多个指定配置文件处于活动状态时,组件有资格注册。使用我们前面的示例,我们可以将 dataSource
配置重写如下:
-
Java
-
Kotlin
@Configuration
@Profile("development")
public class StandaloneDataConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:com/bank/config/sql/schema.sql")
.addScript("classpath:com/bank/config/sql/test-data.sql")
.build();
}
}
@Configuration
@Profile("development")
class StandaloneDataConfig {
@Bean
fun dataSource(): DataSource {
return EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:com/bank/config/sql/schema.sql")
.addScript("classpath:com/bank/config/sql/test-data.sql")
.build()
}
}
- Java
-
@Configuration @Profile("production") public class JndiDataConfig { @Bean(destroyMethod = "") [id="CO1-1"][id="CO1-1"][id="CO1-1"](1) public DataSource dataSource() throws Exception { Context ctx = new InitialContext(); return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource"); } }
<1> `@Bean(destroyMethod = "")` 禁用默认销毁方法推断。
- Kotlin
-
@Configuration @Profile("production") class JndiDataConfig { @Bean(destroyMethod = "") [id="CO2-1"][id="CO1-2"][id="CO2-1"](1) fun dataSource(): DataSource { val ctx = InitialContext() return ctx.lookup("java:comp/env/jdbc/datasource") as DataSource } }
<1> `@Bean(destroyMethod = "")` 禁用默认销毁方法推断。
如前所述,对于 |
配置文件字符串可以包含一个简单的配置文件名称(例如,production
)或一个配置文件表达式。配置文件表达式允许表达更复杂的配置文件逻辑(例如,production & us-east
)。配置文件表达式支持以下运算符:
-
!
: 配置文件的逻辑NOT
-
&
: 配置文件的逻辑AND
-
|
: 配置文件的逻辑OR
您不能在不使用括号的情况下混合使用 |
您可以将 @Profile
用作 元注解,以创建自定义组合注解。以下示例定义了一个自定义 @Production
注解,您可以将其用作 @Profile("production")
的替代品:
-
Java
-
Kotlin
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Profile("production")
public @interface Production {
}
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@Profile("production")
annotation class Production
如果 |
@Profile
也可以在方法级别声明,以仅包含配置类的一个特定 bean(例如,用于特定 bean 的替代变体),如以下示例所示:
- Java
-
@Configuration public class AppConfig { @Bean("dataSource") @Profile("development") [id="CO3-1"][id="CO1-3"][id="CO3-1"](1) public DataSource standaloneDataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.HSQL) .addScript("classpath:com/bank/config/sql/schema.sql") .addScript("classpath:com/bank/config/sql/test-data.sql") .build(); } @Bean("dataSource") @Profile("production") [id="CO3-2"][id="CO1-4"][id="CO3-2"](2) public DataSource jndiDataSource() throws Exception { Context ctx = new InitialContext(); return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource"); } }
<1> `standaloneDataSource` 方法仅在 `development` 配置文件中可用。 <1> `jndiDataSource` 方法仅在 `production` 配置文件中可用。
- Kotlin
-
@Configuration class AppConfig { @Bean("dataSource") @Profile("development") [id="CO4-1"][id="CO1-5"][id="CO4-1"](1) fun standaloneDataSource(): DataSource { return EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.HSQL) .addScript("classpath:com/bank/config/sql/schema.sql") .addScript("classpath:com/bank/config/sql/test-data.sql") .build() } @Bean("dataSource") @Profile("production") [id="CO4-2"][id="CO1-6"][id="CO4-2"](2) fun jndiDataSource() = InitialContext().lookup("java:comp/env/jdbc/datasource") as DataSource }
<1> `standaloneDataSource` 方法仅在 `development` 配置文件中可用。 <1> `jndiDataSource` 方法仅在 `production` 配置文件中可用。
对于 |
XML Bean 定义配置文件
XML 对应的是 <beans>
元素的 profile
属性。我们前面的示例配置可以重写为两个 XML 文件,如下所示:
<beans profile="development"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="...">
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:com/bank/config/sql/schema.sql"/>
<jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/>
</jdbc:embedded-database>
</beans>
<beans profile="production"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="...">
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
</beans>
也可以避免这种拆分,并在同一个文件中嵌套 <beans/>
元素,如以下示例所示:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="...">
<!-- other bean definitions -->
<beans profile="development">
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:com/bank/config/sql/schema.sql"/>
<jdbc:script location="classpath:com/bank/config/sql/test-data.sql"/>
</jdbc:embedded-database>
</beans>
<beans profile="production">
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource"/>
</beans>
</beans>
spring-bean.xsd
已被限制,仅允许此类元素作为文件中的最后一个元素。这应该有助于提供灵活性,而不会在 XML 文件中造成混乱。
XML 对应部分不支持前面描述的配置文件表达式。但是,可以使用
在前面的示例中,如果 |
激活配置文件
现在我们已经更新了配置,我们仍然需要指示 Spring 哪个配置文件是活动的。如果我们现在启动示例应用程序,我们将看到抛出 NoSuchBeanDefinitionException
,因为容器找不到名为 dataSource
的 Spring bean。
激活配置文件可以通过多种方式完成,但最直接的方法是针对通过 ApplicationContext
可用的 Environment
API 进行编程。以下示例显示了如何执行此操作:
-
Java
-
Kotlin
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("development");
ctx.register(SomeConfig.class, StandaloneDataConfig.class, JndiDataConfig.class);
ctx.refresh();
val ctx = AnnotationConfigApplicationContext().apply {
environment.setActiveProfiles("development")
register(SomeConfig::class.java, StandaloneDataConfig::class.java, JndiDataConfig::class.java)
refresh()
}
此外,您还可以通过 spring.profiles.active
属性声明性地激活配置文件,该属性可以通过系统环境变量、JVM 系统属性、web.xml
中的 servlet 上下文参数,甚至作为 JNDI 中的条目来指定(请参阅 PropertySource
抽象)。在集成测试中,可以使用 spring-test
模块中的 @ActiveProfiles
注解声明活动配置文件(请参阅 带有环境配置文件的上下文配置)。
请注意,配置文件不是 “非此即彼” 的命题。您可以同时激活多个配置文件。通过编程方式,您可以向 setActiveProfiles()
方法提供多个配置文件名称,该方法接受 String…
可变参数。以下示例激活多个配置文件:
-
Java
-
Kotlin
ctx.getEnvironment().setActiveProfiles("profile1", "profile2");
ctx.getEnvironment().setActiveProfiles("profile1", "profile2")
声明性地,spring.profiles.active
可以接受逗号分隔的配置文件名称列表,如以下示例所示:
-Dspring.profiles.active="profile1,profile2"
默认配置文件
默认配置文件表示如果没有配置文件处于活动状态时启用的配置文件。考虑以下示例:
-
Java
-
Kotlin
@Configuration
@Profile("default")
public class DefaultDataConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:com/bank/config/sql/schema.sql")
.build();
}
}
@Configuration
@Profile("default")
class DefaultDataConfig {
@Bean
fun dataSource(): DataSource {
return EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:com/bank/config/sql/schema.sql")
.build()
}
}
如果 beans-definition-profiles-enable,则创建 dataSource
。您可以将其视为为 一个或多个
bean 提供默认定义的一种方式。如果任何配置文件被启用,则默认配置文件不适用。
默认配置文件的名称是 default
。您可以通过在 Environment
上使用 setDefaultProfiles()
或通过声明方式使用 spring.profiles.default
属性来更改默认配置文件的名称。
PropertySource
抽象
Spring 的 Environment
抽象提供了对可配置属性源层次结构的搜索操作。考虑以下列表:
-
Java
-
Kotlin
ApplicationContext ctx = new GenericApplicationContext();
Environment env = ctx.getEnvironment();
boolean containsMyProperty = env.containsProperty("my-property");
System.out.println("Does my environment contain the 'my-property' property? " + containsMyProperty);
val ctx = GenericApplicationContext()
val env = ctx.environment
val containsMyProperty = env.containsProperty("my-property")
println("Does my environment contain the 'my-property' property? $containsMyProperty")
在前面的代码片段中,我们看到了一种高级方式来询问 Spring 当前环境是否定义了 my-property
属性。为了回答这个问题,Environment
对象对一组 PropertySource
对象执行搜索。PropertySource
是对任何键值对源的简单抽象,Spring 的 StandardEnvironment
配置了两个 PropertySource 对象——一个代表 JVM 系统属性集(System.getProperties()
),另一个代表系统环境变量集(System.getenv()
)。
这些默认属性源存在于 |
具体来说,当您使用 StandardEnvironment
时,对 env.containsProperty("my-property")
的调用如果 my-property
系统属性或 my-property
环境变量在运行时存在,则返回 true。
执行的搜索是分层的。默认情况下,系统属性优先于环境变量。因此,如果在调用
|
最重要的是,整个机制是可配置的。也许您有一个自定义的属性源,您想将其集成到此搜索中。为此,请实现并实例化您自己的 PropertySource
并将其添加到当前 Environment
的 PropertySources
集中。以下示例显示了如何执行此操作:
-
Java
-
Kotlin
ConfigurableApplicationContext ctx = new GenericApplicationContext();
MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
sources.addFirst(new MyPropertySource());
val ctx = GenericApplicationContext()
val sources = ctx.environment.propertySources
sources.addFirst(MyPropertySource())
在前面的代码中,MyPropertySource
已以最高优先级添加到搜索中。如果它包含 my-property
属性,则检测并返回该属性,优先于任何其他 PropertySource
中的 my-property
属性。https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/MutablePropertySources.html[MutablePropertySources
] API 提供了许多方法,允许精确操作属性源集。
使用 @PropertySource
@PropertySource
注解提供了一种方便的声明性机制,用于向 Spring 的 Environment
添加 PropertySource
。
给定一个名为 app.properties
的文件,其中包含键值对 testbean.name=myTestBean
,以下 @Configuration
类使用 @PropertySource
,以便调用 testBean.getName()
返回 myTestBean
:
-
Java
-
Kotlin
@Configuration
@PropertySource("classpath:/com/myco/app.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
@Configuration
@PropertySource("classpath:/com/myco/app.properties")
class AppConfig {
@Autowired
private lateinit var env: Environment
@Bean
fun testBean() = TestBean().apply {
name = env.getProperty("testbean.name")!!
}
}
@PropertySource
资源位置中存在的任何 ${…}
占位符都将根据环境中已注册的属性源集进行解析,如以下示例所示:
-
Java
-
Kotlin
@Configuration
@PropertySource("classpath:/com/${my.placeholder:default/path}/app.properties")
public class AppConfig {
@Autowired
Environment env;
@Bean
public TestBean testBean() {
TestBean testBean = new TestBean();
testBean.setName(env.getProperty("testbean.name"));
return testBean;
}
}
@Configuration
@PropertySource("classpath:/com/\${my.placeholder:default/path}/app.properties")
class AppConfig {
@Autowired
private lateinit var env: Environment
@Bean
fun testBean() = TestBean().apply {
name = env.getProperty("testbean.name")!!
}
}
假设 my.placeholder
存在于已注册的某个属性源中(例如,系统属性或环境变量),则占位符将解析为相应的值。如果不存在,则使用 default/path
作为默认值。如果未指定默认值且无法解析属性,则会抛出 IllegalArgumentException
。
|
语句中的占位符解析
从历史上看,元素中的占位符值只能根据 JVM 系统属性或环境变量进行解析。现在不再是这样了。由于 Environment
抽象已集成到整个容器中,因此可以轻松地通过它路由占位符的解析。这意味着您可以以任何您喜欢的方式配置解析过程。您可以更改通过系统属性和环境变量搜索的优先级,或完全删除它们。您还可以根据需要添加自己的属性源。
具体来说,无论 customer
属性在哪里定义,只要它在 Environment
中可用,以下语句都将起作用:
<beans>
<import resource="com/bank/service/${customer}-config.xml"/>
</beans>