I have a main app-context.xml that defines a property placeholder with two locations: default properties file and an optional override file:
<context:property-placeholder
location="classpath:config.properties,${configOverride}"
ignore-resource-not-found="true" />
The optional override location allows specifying another properties file (e.g. "-DconfigOverride=file:/home/app/config.properties") with only the properties that should be overridden.
For my unit tests, I'm using a test context that imports app-context.xml:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-context.xml"})
public class UserServiceTest {
...
}
How can I set system properties or environment variables within the application before the application context is loaded? I would like to achieve the same effect as setting "-DconfigOverride=classpath:testConfig.properties" across all test classes without having to specify a command line arg, if possible.
Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.
You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration.
One other alternative is setting the environment property in a @BeforeClass annotated method, which will be invoked before the Context Configuration happens.
@BeforeClass
public static void setSystemProps() {
System.setProperty("configOverride", "yourVal");
}
Thinking of ,
SpringJUnit4ClassRunner
and setting the system property
configOverride
in its constructor/initialization blockExtendedSpringJUnit4ClassRunner
to @RunWith
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With