Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set System Properties or Environment Variables Before Property Placeholder with SpringJunit4ClassRunner

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.

like image 606
andy Avatar asked May 30 '12 18:05

andy


People also ask

How do I set environment properties in spring boot?

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.

What 2 types of file formats can use to inject properties into the Spring environment object?

You can use properties files, YAML files, environment variables and command-line arguments to externalize configuration.


2 Answers

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");
}
like image 107
kevin Avatar answered Sep 18 '22 16:09

kevin


Thinking of ,

  1. Extending SpringJUnit4ClassRunner and setting the system property configOverride in its constructor/initialization block
  2. Then passing ExtendedSpringJUnit4ClassRunner to @RunWith
like image 28
Ahamed Mustafa M Avatar answered Sep 21 '22 16:09

Ahamed Mustafa M