Home > other >  How to load properties based on environment in spring boot jar
How to load properties based on environment in spring boot jar

Time:10-31

I'm building a reusable library in spring boot which makes Rest API calls and do some validation. This will be built as JAR The goal is to use this library as maven dependency by adding in pom.xml in other spring boot projects.

Problem is how does the library knows which environment properties to load. Since its not running on any server. For example: Calling application will include as dependency and gets deployed in dit environment. I want library to pick up dit properties such as url, tokens etc Any suggestions on how to achieve this.

CodePudding user response:

If you use application.properties, you can extend your app's file by your library's one like so. Or declare your library's file using @PropertySource.

Or you could pass some stuff to your library, which then sets the config values using @Value.

CodePudding user response:

If you want to create reusable library you should avoid reading the configuration from any specific location. While there may be some exception to this rule, in general reading the configuration from specific location (say environment variable or property file) will limit the reusability and the testability of your library.

I think the best approach is to separate your code in two. The library itself without any dependency to Spring. You could easily configure it using constructor injection, builders or other suitable pattern. For example if you want to set the URL to connect to, you can use the constructor:

public class ExampleClient {

    private final String url;

    public ExampleClient(String url) {
        this.url = url;
    }

    // the rest of the class
}

As your library does not depend on Spring or any environment it is very easy to be tested. And increases the reusability as it does not make any assumption about the environment it will run in. Even if you plan to use it for single environment, one day the environment or the requirements may change.

Then you can create your own auto-configuration that will create ExampleClient instance and configure it with the appropriate URL. How it will get the URL depends on you specific requirements, but in most cases is best to use Externalized Configuration. It will give you a lot of flexibility.

  • Related