'Inject application properties without Spring
I would like a simple, preferably annotation-based way to inject external properties into a java program, without using the spring framework (org.springframework.beans.factory.annotation.Value;
)
SomeClass.java
@Value("${some.property.name}")
private String somePropertyName;
application.yml
some:
property:
name: someValue
Is there a recommended way to do this in the standard library?
Solution 1:[1]
I ended up using apache commons configuration:
pom.xml:
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.6</version>
</dependency>
src/.../PropertiesLoader.java
PropertiesConfiguration config = new PropertiesConfiguration();
config.load(PROPERTIES_FILENAME);
config.getInt("someKey");
/src/main/resources/application.properties
someKey: 2
I did not want to turn my library into a Spring application (I wanted @Value
annotations, but no application context + @Component
, extra beans, extra Spring ecosystem/baggage which doesn't make sense in my project).
Solution 2:[2]
Define application properties here /src/main/resources/application.properties
Define PropertiesLoader class
public class PropertiesLoader {
public static Properties loadProperties() throws IOException {
Properties configuration = new Properties();
InputStream inputStream = PropertiesLoader.class
.getClassLoader()
.getResourceAsStream("application.properties");
configuration.load(inputStream);
inputStream.close();
return configuration;
}
}
Inject property value in the required class like below,
Properties conf = PropertiesLoader.loadProperties();
String property = configuration.getProperty(key);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Stone |