Create your own configuration properties in Quarkus

Lionel P. Albus
2 min readFeb 5, 2021

In real work, many times we wanna use a constant variable or set config in specific tasks for sharing variables in the whole project. Let’s see how can we set it.

Configuration reference

Create a java class

In the example, we create the class name Config to keep the init config of our project. We can create a java class with the following content:

package th.co.singh.config;

import io.quarkus.arc.config.ConfigProperties;
import io.quarkus.runtime.annotations.ConfigItem;

@ConfigProperties(prefix = "config") // set prefix name here
public class Config {
@ConfigItem(
name = "server-address", // set item name here
defaultValue = "12.111.11.111" // set defaultValue here
)
public String serverAddress;

@ConfigItem(
name = "port",
defaultValue = "22"
)
public String port;

@ConfigItem(
name = "user-name",
defaultValue = "user"
)
public String userName;

@ConfigItem(
name = "password",
defaultValue = "1234"
)
public String password;
}

Create the configuration

By default, Quarkus reads configuration properties from several sources. For this example, we will use an application configuration file located in src/main/resources/application.properties. We can set variables following content:

#Example config
# replace your value here
config.server-address = "12.111.11.111"
config.port = "22"
config.user-name = "user"
config.password = "1234"

In the example above, we will see config properties name and config item name that we set in the Config class will reference in configuration variables in the application.properties file.

Get values from Config

When we wanna use a value from config we can get value by Inject config to java class that we wanna use a value. Let’s see how to get it to work?

package th.co.singh.config;

import lombok.extern.slf4j.Slf4j;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Slf4j
@Path("/api")
public class Resource {

@Inject // Inject config class that we wanna use a value
Config config;

@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
// we can get a value following the code below
// config meaning name of Config class that we inject in
// serverAddress meaning name of variables that we specific
log.info("server address: " + config.serverAddress);
log.info("server port: " + config.port);
log.info("server user name: " + config.userName);
log.info("server password: " + config.password);

return "Example get value from config work!!!";
}
}

When you run the code, you will see results like this.

you can see our code here Lionel-P-Albus/quarkus-configuration

I hope this article will help you can create and use config on your own. Thank for reading it!!! 👏👏👏

--

--