#BAEL-2888- Reloading Properties Files in Spring (#7392)

Code samples for BAEL-2888
This commit is contained in:
maryarm 2019-07-27 16:50:52 +04:30 committed by Josh Cummings
parent 71af0f793c
commit 8d62e17b8e
19 changed files with 588 additions and 0 deletions

17
spring-boot-properties/.gitignore vendored Normal file
View File

@ -0,0 +1,17 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear
*.ipr
*.iml
*.iws

View File

@ -0,0 +1,2 @@
### Relevant Articles:
- [Reloading Properties in Spring](https://www.baeldung.com/reloading-properties-files-in-spring/)

View File

@ -0,0 +1 @@
application.theme.color=blue

View File

@ -0,0 +1 @@
application.theme.background=red

View File

@ -0,0 +1,104 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-boot-properties</artifactId>
<packaging>jar</packaging>
<name>spring-boot-properties</name>
<description>Spring Boot Properties Module</description>
<parent>
<artifactId>parent-boot-2</artifactId>
<groupId>com.baeldung</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>${commons-configuration.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<finalName>spring-boot-properties</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntTest.java</exclude>
</excludes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
<commons-configuration.version>1.10</commons-configuration.version>
</properties>
</project>

View File

@ -0,0 +1,44 @@
package com.baeldung.properties;
import com.baeldung.properties.configs.ReloadableProperties;
import java.io.File;
import java.util.Properties;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
@SpringBootApplication
public class SpringBootPropertiesApplication {
@Bean
@ConditionalOnProperty(name = "spring.config.location", matchIfMissing = false)
public PropertiesConfiguration propertiesConfiguration(
@Value("${spring.config.location}") String path,
@Value("${spring.properties.refreshDelay}") long refreshDelay) throws Exception {
String filePath = path.substring("file:".length());
PropertiesConfiguration configuration = new PropertiesConfiguration(new File(filePath).getCanonicalPath());
FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy();
fileChangedReloadingStrategy.setRefreshDelay(refreshDelay);
configuration.setReloadingStrategy(fileChangedReloadingStrategy);
return configuration;
}
@Bean
@ConditionalOnBean(PropertiesConfiguration.class)
@Primary
public Properties properties(PropertiesConfiguration propertiesConfiguration) throws Exception {
ReloadableProperties properties = new ReloadableProperties(propertiesConfiguration);
return properties;
}
public static void main(String[] args) {
SpringApplication.run(SpringBootPropertiesApplication.class, args);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.properties.configs;
public class PropertiesException extends RuntimeException {
public PropertiesException() {
}
public PropertiesException(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.properties.configs;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;
import javax.naming.OperationNotSupportedException;
import org.apache.commons.configuration.PropertiesConfiguration;
public class ReloadableProperties extends Properties {
private PropertiesConfiguration propertiesConfiguration;
public ReloadableProperties(PropertiesConfiguration propertiesConfiguration) throws IOException {
super.load(new FileReader(propertiesConfiguration.getFile()));
this.propertiesConfiguration = propertiesConfiguration;
}
@Override
public synchronized Object setProperty(String key, String value) {
propertiesConfiguration.setProperty(key, value);
return super.setProperty(key, value);
}
@Override
public String getProperty(String key) {
String val = propertiesConfiguration.getString(key);
super.setProperty(key, val);
return val;
}
@Override
public String getProperty(String key, String defaultValue) {
String val = propertiesConfiguration.getString(key, defaultValue);
super.setProperty(key, val);
return val;
}
@Override
public synchronized void load(Reader reader) throws IOException {
throw new PropertiesException(new OperationNotSupportedException());
}
@Override
public synchronized void load(InputStream inStream) throws IOException {
throw new PropertiesException(new OperationNotSupportedException());
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.properties.configs;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.springframework.core.env.PropertySource;
import org.springframework.util.StringUtils;
public class ReloadablePropertySource extends PropertySource {
PropertiesConfiguration propertiesConfiguration;
public ReloadablePropertySource(String name, PropertiesConfiguration propertiesConfiguration) {
super(name);
this.propertiesConfiguration = propertiesConfiguration;
}
public ReloadablePropertySource(String name, String path) {
super(StringUtils.isEmpty(name) ? path : name);
try {
this.propertiesConfiguration = new PropertiesConfiguration(path);
FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
strategy.setRefreshDelay(1000);
this.propertiesConfiguration.setReloadingStrategy(strategy);
} catch (Exception e) {
throw new PropertiesException(e);
}
}
@Override
public Object getProperty(String s) {
return propertiesConfiguration.getProperty(s);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.properties.configs;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
@Configuration
public class ReloadablePropertySourceConfig {
private ConfigurableEnvironment env;
public ReloadablePropertySourceConfig(@Autowired ConfigurableEnvironment env) {
this.env = env;
}
@Bean
@ConditionalOnProperty(name = "spring.config.location", matchIfMissing = false)
public ReloadablePropertySource reloadablePropertySource(PropertiesConfiguration properties) {
ReloadablePropertySource ret = new ReloadablePropertySource("dynamic", properties);
MutablePropertySources sources = env.getPropertySources();
sources.addFirst(ret);
return ret;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.properties.configs;
import java.io.IOException;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.FileUrlResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
public class ReloadablePropertySourceFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String s, EncodedResource encodedResource) throws IOException {
Resource internal = encodedResource.getResource();
if (internal instanceof FileSystemResource) {
return new ReloadablePropertySource(s, ((FileSystemResource) internal).getPath());
}
if (internal instanceof FileUrlResource) {
return new ReloadablePropertySource(s, ((FileUrlResource) internal)
.getURL()
.getPath());
}
return super.createPropertySource(s, encodedResource);
}
}

View File

@ -0,0 +1,3 @@
management.endpoints.web.exposure.include=refresh
spring.properties.refreshDelay=1000
spring.config.location=file:extra.properties

View File

@ -0,0 +1,161 @@
package com.baeldung.properties;
import com.baeldung.properties.beans.ConfigurationPropertiesRefreshConfigBean;
import com.baeldung.properties.beans.EnvironmentConfigBean;
import com.baeldung.properties.beans.PropertiesConfigBean;
import com.baeldung.properties.beans.ValueRefreshConfigBean;
import java.io.FileOutputStream;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBootPropertiesTestApplication.class)
public class PropertiesReloadIntegrationTest {
protected MockMvc mvc;
protected long refreshDelay = 3000;
@Autowired
WebApplicationContext webApplicationContext;
@Autowired
ValueRefreshConfigBean valueRefreshConfigBean;
@Autowired
ConfigurationPropertiesRefreshConfigBean configurationPropertiesRefreshConfigBean;
@Autowired
EnvironmentConfigBean environmentConfigBean;
@Autowired
PropertiesConfigBean propertiesConfigBean;
@Autowired
@Qualifier("singletonValueRefreshConfigBean")
ValueRefreshConfigBean singletonValueRefreshConfigBean;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.build();
createConfig("extra.properties", "application.theme.color", "blue");
createConfig("extra2.properties", "application.theme.background", "red");
Thread.sleep(refreshDelay);
callRefresh();
}
@After
public void tearDown() throws Exception {
createConfig("extra.properties", "application.theme.color", "blue");
createConfig("extra2.properties", "application.theme.background", "red");
}
@Test
public void givenEnvironmentReader_whenColorChanged_thenExpectChangeValue() throws Exception {
Assert.assertEquals("blue", environmentConfigBean.getColor());
createConfig("extra.properties", "application.theme.color", "red");
Thread.sleep(refreshDelay);
Assert.assertEquals("red", environmentConfigBean.getColor());
}
@Test
public void givenEnvironmentReader_whenBackgroundChanged_thenExpectChangeValue() throws Exception {
Assert.assertEquals("red", environmentConfigBean.getBackgroundColor());
createConfig("extra2.properties", "application.theme.background", "blue");
Thread.sleep(refreshDelay);
Assert.assertEquals("blue", environmentConfigBean.getBackgroundColor());
}
@Test
public void givenPropertiesReader_whenColorChanged_thenExpectChangeValue() throws Exception {
Assert.assertEquals("blue", propertiesConfigBean.getColor());
createConfig("extra.properties", "application.theme.color", "red");
Thread.sleep(refreshDelay);
Assert.assertEquals("red", propertiesConfigBean.getColor());
}
@Test
public void givenRefreshScopedValueReader_whenColorChangedAndRefreshCalled_thenExpectChangeValue() throws Exception {
Assert.assertEquals("blue", valueRefreshConfigBean.getColor());
createConfig("extra.properties", "application.theme.color", "red");
Thread.sleep(refreshDelay);
Assert.assertEquals("blue", valueRefreshConfigBean.getColor());
callRefresh();
Assert.assertEquals("red", valueRefreshConfigBean.getColor());
}
@Test
public void givenSingletonRefreshScopedValueReader_whenColorChangedAndRefreshCalled_thenExpectOldValue() throws Exception {
Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor());
createConfig("extra.properties", "application.theme.color", "red");
Thread.sleep(refreshDelay);
Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor());
callRefresh();
Assert.assertEquals("blue", singletonValueRefreshConfigBean.getColor());
}
@Test
public void givenRefreshScopedConfigurationPropertiesReader_whenColorChangedAndRefreshCalled_thenExpectChangeValue() throws Exception {
Assert.assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor());
createConfig("extra.properties", "application.theme.color", "red");
Thread.sleep(refreshDelay);
Assert.assertEquals("blue", configurationPropertiesRefreshConfigBean.getColor());
callRefresh();
Assert.assertEquals("red", configurationPropertiesRefreshConfigBean.getColor());
}
public void callRefresh() throws Exception {
MvcResult mvcResult = mvc
.perform(MockMvcRequestBuilders
.post("/actuator/refresh")
.accept(MediaType.APPLICATION_JSON_VALUE))
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
Assert.assertEquals(response.getStatus(), 200);
}
public void createConfig(String file, String key, String value) throws Exception {
FileOutputStream fo = new FileOutputStream(file);
fo.write(String
.format("%s=%s", key, value)
.getBytes());
fo.close();
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.properties;
import com.baeldung.properties.beans.ValueRefreshConfigBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.test.context.web.WebAppConfiguration;
@SpringBootApplication
@WebAppConfiguration
public class SpringBootPropertiesTestApplication {
@Bean("singletonValueRefreshConfigBean")
@RefreshScope
@Scope("singleton")
public ValueRefreshConfigBean singletonValueRefreshConfigBean(@Value("${application.theme.color:null}") String val) {
return new ValueRefreshConfigBean(val);
}
@Bean
@RefreshScope
public ValueRefreshConfigBean valueRefreshConfigBean(@Value("${application.theme.color:null}") String val) {
return new ValueRefreshConfigBean(val);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.properties.beans;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "application.theme")
@RefreshScope
public class ConfigurationPropertiesRefreshConfigBean {
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.properties.beans;
import com.baeldung.properties.configs.ReloadablePropertySourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = "file:extra2.properties", factory = ReloadablePropertySourceFactory.class)
public class EnvironmentConfigBean {
private Environment environment;
public EnvironmentConfigBean(@Autowired Environment environment) {
this.environment = environment;
}
public String getColor() {
return environment.getProperty("application.theme.color");
}
public String getBackgroundColor() {
return environment.getProperty("application.theme.background");
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.properties.beans;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class PropertiesConfigBean {
private Properties properties;
public PropertiesConfigBean(@Autowired Properties properties) {
this.properties = properties;
}
public String getColor() {
return properties.getProperty("application.theme.color");
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.properties.beans;
public class ValueRefreshConfigBean {
private String color;
public ValueRefreshConfigBean(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}

View File

@ -0,0 +1,3 @@
management.endpoints.web.exposure.include=refresh
spring.properties.refreshDelay=1000
spring.config.location=file:extra.properties