Skip to content

Commit e09ba8e

Browse files
adasioomaibin
authored andcommitted
BAEL-923 How to inject a value from properties to a class not managed by Spring? (eugenp#1878)
* adam.zawada@gmail.com - Different Types of Bean Injection in Spring * adam.zawada@gmail.com - Different Types of Bean Injection in Spring switch to Java based configuration * BAEL-895 calculate the period/duration between two dates in Java 8 * clean old PR * BAEL-923 How to inject a value from properties to a class not managed by Spring? * clean PR
1 parent e338d3e commit e09ba8e

3 files changed

Lines changed: 57 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.baeldung.util;
2+
3+
import java.io.IOException;
4+
import java.io.InputStream;
5+
import java.util.Properties;
6+
7+
public class PropertiesLoader {
8+
9+
public static Properties loadProperties(String resourceFileName) throws IOException {
10+
Properties configuration = new Properties();
11+
InputStream inputStream = PropertiesLoader.class
12+
.getClassLoader()
13+
.getResourceAsStream(resourceFileName);
14+
configuration.load(inputStream);
15+
inputStream.close();
16+
return configuration;
17+
}
18+
19+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.baeldung.util;
2+
3+
import org.junit.Test;
4+
5+
import java.io.IOException;
6+
import java.util.Properties;
7+
8+
import static org.junit.Assert.assertEquals;
9+
10+
public class PropertiesLoaderTest {
11+
12+
@Test
13+
public void loadProperties_whenPropertyReaded_thenSuccess() throws IOException {
14+
//given
15+
final String RESOURCE_FILE_NAME = "configuration.properties";
16+
17+
final String SAMPLE_CONF_ENTRY = "sampleConfEntry";
18+
final String COLON_SEPARATED_CONF_ENTRY = "colonSeparatedEntry";
19+
20+
final String GIVEN_CONF_ENTRY_VALUE = "sample String value";
21+
final String COLON_SEPARATED_CONF_ENTRY_VALUE = "colon separated entry value";
22+
23+
//when
24+
Properties config = PropertiesLoader.loadProperties(RESOURCE_FILE_NAME);
25+
26+
String sampleConfEntryValue = config.getProperty(SAMPLE_CONF_ENTRY);
27+
String colonSeparatedConfEntryValue = config.getProperty(COLON_SEPARATED_CONF_ENTRY);
28+
29+
//then
30+
assertEquals(GIVEN_CONF_ENTRY_VALUE, sampleConfEntryValue);
31+
assertEquals(COLON_SEPARATED_CONF_ENTRY_VALUE, colonSeparatedConfEntryValue);
32+
33+
}
34+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# this is sample property file for PropertiesLoaderTest configuration needs
2+
! this is also a comment
3+
sampleConfEntry = sample String value
4+
colonSeparatedEntry : colon separated entry value

0 commit comments

Comments
 (0)