频道
bg

PropertySource & Environment

coding二月 14, 20161mins
Spring Framework

在Spring 3.1之前,注册一个配置文件的唯一方法就是

bash

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

Spring 3.1引入了PropertySourceEnvironment接口,可以通过@PropertySource注解来注册

bash

@Configuration
@PropertySource("classpath:some.properties")
public class ApplicationConfiguration

并且从Spring 3.1之后,<context:property-placeholder>实际底层注册的是PropertySourcesPlaceholderConfigurer对象。 这个对象具有更好的扩展性并且和EnvironmentPropertySource接口交互。

使用PropertySourceH2

推荐的使用方式是

bash

@Configuration
@PropertySource("classpath:some.properties")
public class ApplicationConfiguration

然后注入environment

bash

@Inject
private Environment environment;

通过Environment实例来读取配置

bash

environment.getProperty("foo.bar")

在Spring 3.2中使用@Value注解H3

使用@PropertySource注解并没有注册PropertySourcesPlaceholderConfigurer(或者PropertyPlaceholderConfigurer)对象。@Value和Environment的机制是独立的,并且environment是推荐的方式。

如果仍想使用@Value注解,可以注册PropertySourcesPlaceholderConfigurer对象来让其调用Environment接口达到目的。

Mocking PropertySourceH2

Mock一个PropertySource,添加如下代码到测试代码中

bash

public static class PropertyMockingApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
MockPropertySource mockEnvVars = new MockPropertySource().withProperty("bundling.enabled", false);
propertySources.replace(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, mockEnvVars);
}
}

bash

@ContextConfiguration(classes = ApplicationConfiguration.class, initializers = MyIntegrationTest.TestApplicationContextInitializer.class)

或者直接添加Environment的mock对象

bash

public static class PropertyMockingApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
MockEnvironment mockEnvironment = new MockEnvironment();
applicationContext.setEnvironment(mockEnvironment);
}
}

评论


新的评论

匹配您的Gravatar头像

Joen Yu

@2022 JoenYu, all rights reserved. Made with love.