Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 652
ealfonso Avatar asked Nov 28 '16 01:11

ealfonso


People also ask

How do you inject a property?

In property injection, we need to pass object of the dependent class through a public property of the client class. Let's use the below example for the implementation of the Property Injection or even it is called Setter Injection as value or dependency getting set in property.

How do I apply different application properties in spring boot?

Properties files are used to keep 'N' number of properties in a single file to run the application in a different environment. In Spring Boot, properties are kept in the application. properties file under the classpath. Note that in the code shown above the Spring Boot application demoservice starts on the port 9090.


1 Answers

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

like image 137
ealfonso Avatar answered Sep 19 '22 12:09

ealfonso