Inject application properties without Spring

ealfonso picture ealfonso · Nov 28, 2016 · Viewed 7.8k times · Source

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?

Answer

ealfonso picture ealfonso · Nov 29, 2016

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).