There are several approaches for reading properties from a directory in WildFly. We will show in this tutorial two alternative solutions:
Reading properties from a file using MicroProfile Config API
The recommended solution for Microservices deployments is to use the Eclipse MicroProfile Config which is a solution to externalise configuration from microservices. The config properties are provided by ConfigSources. ConfigSources are ordered according to their ordinal, with a higher value taking priority over a lower one.
An in-depth guide on MicroProfile Config API is available here: Configuring Microservices with MicroProfile Configuration
Here we will mention that WildFly ships with a ConfigSource which points to the META-INF/microprofile-config.properties file. All properties contained in that file, will be available to the application.
As an example, if the file microprofile-config.properties contains the following entries:
num.size=5 num.max=100
Then your application can use the num.size and num.max properties tby injecting the @ConfigProperty with their attribute:
@Inject @ConfigProperty(name = "num.size") int numSize; // will be 5 @Inject @ConfigProperty(name = "num.max") int numMax; // will be 100
Reading properties from a configuration directory using plain Java API
The standard approach for reading properties in any Java application is to use the java.util.Properties class which includes the load method to load properties from an InputStream. Here is an example which shows how to read Properties from a file named “file.properties” which is located in the configuration folder of the application server:
Properties prop = new Properties(); String fileName = System.getProperty("jboss.server.config.dir") + "/file.properties"; try(FileInputStream fis = new FileInputStream(fileName)) { prop.load(fis); } // print all properties prop.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v)); // get value by key prop.getProperty("user"); prop.getProperty("password");
That’s it. In this tutorial we have covered two alternative solutions to read property files from a directory using MicroProfile config API and a pure Java solution.