Populating Class From External File in Spring

In our Spring Wicket app we want to populate a Java Class object with values from an external text file.

We'll start in our SpringConfiguration class where we'll load ApplicationContext properties from a local properties file config.properties. We'll use Spring's PropertyOverrideConfigurer override which, from the JavaDoc, is a property resource configurer that overrides bean property values in an application context definition. It pushes values from a properties file into bean definitions.

@Configuration
@ComponentScan(basePackages = "spring.wicket.bootstrap")
public class SpringConfiguration {
private static final Logger log = LoggerFactory.getLogger(SpringConfiguration.class);

@Bean
public static PropertyOverrideConfigurer propertyOverride() {
    final PropertyOverrideConfigurer properties = new PropertyOverrideConfigurer();
     Properties jProperties = new Properties();
    try {
        jProperties.load(
                SpringConfiguration.class.getResourceAsStream("/config.properties"));
    } catch (IOException e) {
        log.error(e.getMessage());
    }
    Resource location = new FileSystemResource(
            jProperties.getProperty("spring.properties.file"));
    properties.setLocation(location);

    return properties;
}

@Bean
public PropertyClass propertyClass() {
    PropertyClass properties = new PropertyClass();
    return properties;
}

The local properties file provides the location of the external resource file in spring.properties.file, a location in my home directory outside the project area. Something like

spring.properties.file=/home/daveburke/my.properties

The Property Class

For purposes of this demo we'll call the Property Class something inventive, like PropertyClass. The PropertyClass Class has a single property, Color. Notice there is no Spring Annotation associated with this Class. It is set above in the SpringConfiguration class with the @Bean annotation where we configure the bean and populate it from the external resource with Spring's Property Override Configurer.

package spring.wicket.bootstrap.dao;

public class PropertyClass {
    private String color;

    public void setColor(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }
}

Naming Properties in External Resource File

The entry in our external file for the Color property of PropertyClass looks like this.

propertyClass.color=green

Notice the class is lower case, with “.” then property.

The Wicket Display

We instantiate our PropertyClass @SpringBean and use the propertyClass.getColor() as we normally would, with the class fully populated.

And on the page we see green!

Source Code Notes for this Post

Topics discussed in this post can be found in the v0.0.1 Branch of my Spring-Wicket-Bootstrap GitHub repo and viewed online here.

More Like This Post