Spring JUnit ApplicationContextInitializer Parameters

We have implemented the extended .properties format. Such a properties file may contain an optional include property. The value of these properties is the path to the classes of other property files for recursive loading.

I could customize the Spring environment for my application, but I had a problem using this mechanism using SpringJUnit4ClassRunner .

I thought I could use the initializer property of the ContextConfiguration annotation, but it seems that it can only be created using the no-arg constructor.

I need to provide it with the root file of the property file hierarchy. Ultimately, this may be another annotation in my test class, but then again, how can I access it?

The only thing I have found so far is to set this file as a system property in the static initializer of the test class. ugly:

 @ActiveProfiles("qacs.controller.channels=mock") @ContextConfiguration(initializer=ContainerTestContextInitializer.class) public class QacsControllerTest { static { System.setProperty(ContainerTestContextInitializer.SYSTEM_PROPERTY, "classpath:com/xxx/qacs/QacsControllerTest.properties"); } @Test void test() {} } } public class ContainerTestContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { public static final String SYSTEM_PROPERTY = "icomp.test.properties"; @Override public void initialize(ConfigurableApplicationContext pApplicationContext) { String path = System.getProperty(SYSTEM_PROPERTY); if (path == null) { throw new IllegalStateException("Missing system property " + SYSTEM_PROPERTY); } final DefaultPropertiesLoader loader; loader = new DefaultPropertiesLoader(System.getProperties()); try { loader.load(path); } catch (IOException e) { throw new IllegalStateException(e.getMessage(), e); } MutablePropertySources sources = pApplicationContext.getEnvironment().getPropertySources(); MapPropertySource mps = new MapPropertySource(Launcher.ICOMP_PROPERTY_SOURCE, (Map) loader.getProperties()); sources.addFirst(mps); } } 
+5
source share

Source: https://habr.com/ru/post/1201822/


All Articles