This post is about how to trim string values from Properties files using SpringApplicationBuilder and StandardEnvironment.
Requirements
This post uses the following.
- Java 8 (JDK)
- IntelliJ IDEA Ultimate 2016.3
- Spring Boot 1.5.6.RELEASE
Trim String Values Use-case
Our codes must trim all leading and trailing spaces from parameter values. We have a Properties file as shown in the image below.
The parameter key has a string value with trailing spaces. If we use it as is, we will have the following output.
Read Properties Files Spring Boot
The solution is to trim the String values in the getProperty methods of StandardEnvironment as shown in the code snippet below. First, we create an object of a subclass or anonymous class. Second, we override the 2 getProperty methods to returned trimmed String values. Third, we create an instance of SpringApplicationBuilder and set its environment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | ... StandardEnvironment std = new StandardEnvironment() { @Override public String getProperty(String key) { String tmp = super.getProperty(key); if(tmp != null) { tmp = tmp.trim(); } return tmp; } @Override public String getProperty(String key, String defaultValue) { String tmp = super.getProperty(key, defaultValue); if(tmp != null) { tmp = tmp.trim(); } return tmp; } }; SpringApplicationBuilder builder = new SpringApplicationBuilder( ComTurretaSpringbootTrimStringFromPropertiesApplication.class).environment(std); ApplicationContext ctxtFromBuilder = builder.run(args); SampleBean sb = ctxtFromBuilder.getBean(SampleBean.class); System.out.println(String.format("String value: [%s]", sb.getSampleProperty())); System.out.println(String.format("String value length: [%d]",sb.getSampleProperty().length())); ... |
This outputs:
Download the codes
The codes for this post are available at GitHub.