Search code examples
javaspringspring-bootconcatenationspring-profiles

concatenating profile messages in spring


So I want to concatenate two messages from profile in spring boot. This is my current code (Which is not working because fields are null):

@Profile("fetchGame")
@Service
public class FetchGameApiService {

@Value("${game.api.url}")
private static String LINK;

@Value("${game.api.key}")
private static String KEY;

private static Integer gameId = 1;

private static final String URL = LINK + "/" + gameId + "?key=" + KEY;

//somelogic
}

Here is my profile page:

game.api.url = https://api.rawg.io/api/games
game.api.key = 250b2de5e7734f638760ae2bad8bd29f
this_IS_The_Correct_Url = https://api.rawg.io/api/games/1?key=250b2de5e7734f638760ae2bad8bd29f

Note That I have set active profile in app.properties as: spring.profiles.active = fetchGame My Question is: How is the proper way to concatenate two strings into one from spring profiles? Without having a huge amount of code and make it simple and understandable.


Solution

  • First, spring profile has nothing to do w/ injecting values to fields or method/constructor arguments. Spring profiles allow configuring application context conditionally.

    Here is the list to check out:

    • Make sure to keep fields non-static.
    • Check if PropertySourcesPlaceholderConfigurer bean is registered in context
    • Or use @PropertySource("classpath:application.properties") to set a custom property file to resolve values from.

    Here is the reference documentation on the feature.

    I suggest learning and adopting type safe way to deal w/ configuration properties w/ @ConfigurationProperties annotation.