我在类DefaultConfig中有一个属性test=default,我使用@PropertySource注释使它们可用。
@Configuration
@PropertySource("classpath:default.properties")
public class DefaultConfig {}然后,我希望能够覆盖到test=override,它位于OverrideConfig类的另一个属性文件中,因此我再次使用@PropertySource。
@Configuration
@Import(DefaultConfig.class)
@PropertySource("classpath:override.properties")
public class OverrideConfig {}我配置了一个测试来证明它是有效的。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={OverrideConfig.class})
public class TestPropertyOverride {
@Autowired
private Environment env;
@Test
public void propertyIsOverridden() {
assertEquals("override", env.getProperty("test"));
}
}当然不是这样的。
org.junit.ComparisonFailure: expected:<[override]> but was:<[default]>
最大限度地调试,我可以看到发生了什么:
StandardEnvironment:107 - Adding [class path resource [default.properties]] PropertySource with lowest search precedence
StandardEnvironment:107 - Adding [class path resource [override.properties]] PropertySource with lowest search precedence这似乎是倒退的。我是不是犯了一个简单的错误或者误解了这一点,或者您希望@Import-ed配置类中的@PropertySource定义的属性会被@Import-ing类中的Am @PropertySource中定义的属性覆盖?
发布于 2015-08-29 04:54:00
这是一个由Helder Sousa提供的解决方案,由OP创建,并以a comment of the JIRA issue的形式编写:
spring xml中可用的行为(一个xml导入另一个xml)可以使用嵌套配置来实现:
@Configuration @PropertySource("classpath:default.properties")公共类DefaultConfig {}
@Configuration @PropertySource("classpath:override.properties")公共类OverrideConfig { @Configuration @导入(DefaultConfig.class)静态类InnerConfiguration {} }
通过此设置,将以正确的顺序收集属性。
发布于 2015-03-30 00:13:34
如今,在Spring4中,您可以使用以下内容:
@TestPropertySource(value="classpath:/config/test.properties")这可以用来使用并最终覆盖junit测试的属性:
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(value="classpath:/config/test.properties")发布于 2013-04-25 19:00:26
我目前正在努力解决Spring3.1中类似的情况,但我正在使用一种不同的方法来覆盖属性,因为@PropertySource不支持可选的属性文件:
@Configuration
@PropertySource("classpath:default.properties")
public class BaseConfig {
@Inject
private ApplicationContext context;
@PostConstruct
public void init() throws IOException {
Resource runtimeProps = context.getResource("classpath:override.properties");
if (runtimeProps.exists()) {
MutablePropertySources sources = ((ConfigurableApplicationContext) context).getEnvironment().getPropertySources();
sources.addFirst(new ResourcePropertySource(runtimeProps));
}
}
...看起来,除了正常的@Configuration依赖关系所规定的顺序之外,@Import并不会导致任何特定的bean实例化顺序。强制这种顺序的一种方法是将基本@Configuration实例本身作为依赖项注入。你能不能试试:
@Configuration
@Import(DefaultConfig.class)
@PropertySource("classpath:override.properties")
public class OverrideConfig {
@Inject
private DefaultConfig defaultConfig;
...
}这有帮助吗?也许新的ContextHierarchy注解在这里也会有帮助,但到目前为止我还没有尝试过这个。
https://stackoverflow.com/questions/15577125
复制相似问题