0

I have a class that stores the different endpoints for an API. The class looks like the following:

public class APIEndpoints {

    public static String LOG_IN =  "/api/auth/login";
    public static String LOG_OUT= "/api/auth/logout";
    public static String GET_INSTANCE ="/api/{objectID}/instances?offset={offset}&limit{limit}";

    public static String getInstance(String reportID, int offSet, int limit){
            return GET_INSTANCE.replace("{reportID}",reportID)
                                      .replace("{offset}", String.valueOf(offSet))
                                      .replace("{limit}", String.valueOf(limit));
    }
}

I would like that the endpoints URLs ("api/auth/login" for example) , are loaded from a file, like a endpoints.properties.

I'm using SpringBoot, but it does not allow to inject values on static variables.

What would be the 'most' elegant solution to solve this? How would you approach it?

Thank you.

Gerardo
  • 21
  • 2
  • 7
  • Are you interested in the solution that makes APIEndpoints a spring singleton bean and eliminates the static calls altogether? This bean could be injected into other beans and you could call non-static version of getInstance – Mark Bramnik Mar 09 '21 at 13:31

3 Answers3

1

You can access it by using @Value Annotation as below

@Value("${your.property.name}")
private String property;

and in your endpoints.properties file you have to define It like

your.property.name=propertyValue
Trushit Shekhda
  • 563
  • 7
  • 18
1

The question is already answered: link

Static @Value fields are not recommended, but here is how you can do it:

@Value("${url}")
public void setUrl(String url) {
    APIEndpoints.url = url;
}  
Aidos Rustem
  • 145
  • 8
0

Create a small function which would get the values from the property file and assign it to the static LOG_IN variable:

private static String LOG_IN;
    
@Value("${LOG_IN}")
public void setLoginUrl(String LOG_IN) {
    try {
        APIEndpoints.LOG_IN= LOG_IN;
        } catch (Exception e) {
            e.printStackTrace();
    }
}
İsmail Y.
  • 3,579
  • 5
  • 21
  • 29