[英]Change @PropertySource value in run time
How can I change the value of @PropertySource in run time when the junit test case runs. 当junit测试用例运行时,如何在运行时更改@PropertySource的值。 For example,
例如,
I want to replace the value of below, 我要替换下面的值,
@PropertySource(value = "file:${app.deploy.env}/sample/mine.properties", ignoreResourceNotFound = true)
with 与
value = "classpath:sample/mine.properties"
when junit test runs. 在junit测试运行时。
You can do that if you really want to but I'd not recommend you to do that this way. 如果您确实愿意,可以这样做,但我不建议您这样做。 You first need to figure out which
PropertySource
contains the value. 您首先需要确定哪个
PropertySource
包含该值。 Since you have that annotation in your example, a PropertySource
will be added to the regular ones, probably as the first instance. 由于示例中具有该注释,因此
PropertySource
将添加到常规注释中,可能是第一个实例。
You can inject the Environment
in a managed bean where you want to make that change as a ConfigurableEnvironment
and retrieve the PropertySource
via un call to getMutablePropertySources()
on the environment. 您可以将
Environment
注入到要进行此更改的托管Bean中,作为ConfigurableEnvironment
然后通过取消调用环境中的getMutablePropertySources()
来检索PropertySource
。
Having said that. 话说回来。 Why?
为什么? How is changing such fundamental property of your application is representative of what is going to happen in your app.
如何更改应用程序的这种基本属性代表了应用程序将要发生的事情。 It looks like you are using the Spring runner and you'd like to start your app with different settings in different test methods.
看来您正在使用Spring Runner,并且希望在不同的测试方法中使用不同的设置来启动您的应用。 If that's what you want to do, do not use the runner but manage the context yourself, it's really not that hard.
如果那是您想要做的,不要使用运行器,而是自己管理上下文,这实际上并不难。
For instance, here are JMS-related tests that change the Environment
to test various scenarios. 例如,以下是与JMS相关的测试 ,这些测试更改了
Environment
以测试各种场景。 You can easily load the context with a specific set of keys and a @After
method makes sure to shutdown the context for each test . 您可以使用一组特定的键轻松加载上下文,并且
@After
方法确保关闭每个测试的上下文 。
We use this pattern quite a lot in Spring Boot. 我们在Spring Boot中大量使用了这种模式。 As a matter of a fact, I have a JUnit rule that facilitates all that on my todo list for months now.
事实上,我有一个JUnit规则可以使我的待办事项清单上的所有内容方便使用几个月。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.