Anonymous
Anonymous

Reputation: 1773

How to read Open-Liberty server config property file value in java class?

I have a scenario where I need to read an url from my property file I have created in a server config directory of my created server i.e. C:\<path to liberty installation>\openliberty-21.0.0.11\wlp\usr\servers\TestServer\config\test.properties . I have the property file content something like File :test.properties

downstream_service.url=https:\\abc_service.com

I need to read this url in my crated application's java class somehow and do some operation.This application I am going to deploy in the above server .

e.g.

  public void myMethod(){
      String serviceUrl=<some logic to get >;
    }

Any suggestion would be appreciable to read this value in property file.

Upvotes: 0

Views: 1333

Answers (2)

Anonymous
Anonymous

Reputation: 1773

I found my solution by tweaking some code. I kept the path of properties file in jvm.options like -Djava.test.properties=C:/Users/abc/openliberty-21.0.0.11/wlp/usr/servers/TestServer/config/test.properties Then I was able to get this file path and I loaded this file using bellow code:

Properties props = new Properties();
    try {
        props.load(new FileInputStream(System.getProperty("java.test.properties")));
        System.out.println(props.getProperty("serviceurl"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

Upvotes: 0

M. Broz
M. Broz

Reputation: 738

There are lots of ways to accomplish this, but the one I would recommend would be to leverage MicroProfile Config, as it exists to do exactly what you want with a simple annotation, which would look something like:

@Inject
@ConfigProperty(name="downstream_service.url", 
               defaultValue="setIfApplicable")
private String serviceUrl;

Don't forget to include the mpConfig-2.0 feature in your server.xml (or mpConfig-3.0 or newer if you're already using the jakarta namespace). You would then just need to choose one of the many ways to set the downstream_service.url property, which could be as easy as creating a file named downstream_service.url in ${server.config.dir}/variables and setting its contents to https:\\abc_service.com. Reference the Server Configuration doc for more information.

For more guidance on using mpConfig, take a look at Separating configuration from code in microservices and/or Configuring microservices guides.

Upvotes: 2

Related Questions