user2693135
user2693135

Reputation: 1316

How to Access Spring Application Configuration Values based on Requests?

In one of my Spring Boot application, I have a controller that needs to read from application.yml for accessing an external API. I have organization setup in the external API, similar to github organization, and each organization comes with its own client ID and secret key.

My application.yml looks something like this.

organization:
  abc:
    client:
      clientId: f29e347add73
      clientSecret: dad2404e63ec4cd   

  xyz:
    client:
      clientId: 0884340cf3e793
      clientSecret: a26ff0119d907e9      

Currently, I can pick up a property value in my controller like this.

@Value("${organization.abc.client.clientId}")
private String abcClientId;
@Value("${organization.abc.client.clientSecret}")
private String abcClientSecret;

But what I need to do is, instead of hardcoding, if a request for abc comes, the configuration for abc is picked up and when for xyz comes, the configuration for xyz is picked up. Same for any number of the organization I keep adding to the application.yml file.

Please help me on how to achieve this.

Upvotes: 0

Views: 482

Answers (2)

LHCHIN
LHCHIN

Reputation: 4009

If you can rewrite your applicaiotn.yml as follows, you can read it into a list of object with@ConfigurationProperties.

organization:
  list:
    -
      name: abc
      client:
        clientId: f29e347add73
        clientSecret: dad2404e63ec4cd
    -
      name: xyz
      client:
        clientId: 0884340cf3e793
        clientSecret: a26ff0119d907e9

Create a class to map properties to list of object:

@Service
@ConfigurationProperties(prefix="organization")
public class ConfigurationService {
    private List<Org> list = new ArrayList<>();
    //getters and setters

    public static class Org {
        private String name;
        private Client client;
        //getters and setters
    }

    public static class Client {
        private String clientId;
        private String clientSecret;
        //getter and setter
    }
}

Now you can access this list like...

@Autowired
ConfigurationService configurationService;

Upvotes: 2

Gustavo Passini
Gustavo Passini

Reputation: 2668

You can inject an Environment (initialized by default by Spring Boot) like this:

@Autowired
private Environment env;

And then use it like:

env.getProperty("my-property")

Upvotes: -1

Related Questions