0

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.

2
  • Are you using the .yaml or .properties configuration file? Commented Oct 30, 2021 at 19:27
  • do you know about the existence of profiles? Commented Oct 31, 2021 at 3:27

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@Value is highly discouraged in modern spring
@Eugene Really? Can you link me something, that explains why?
look here for example. relaxed binding is at least one of the reasons
@Eugene Thanks! Didn't think about that before and removed the option from my answer
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.