hatellla
hatellla

Reputation: 5132

Better Practice for getting configuration in Spring Project

Which is a better practice to do? Should I take out all the configuration that I am using in code below in the spring file, which should take from some config file? Or using them directly in code is fine?

String endPoint = "dsadas";  
HttpClientConfig httpClientConfig = new HttpClientConfig
                .Builder(endPoint)
                .multiThreaded(true)
                .readTimeout(50000)
                .connTimeout(60000)
                .maxTotalConnection(40)
                .build();

Upvotes: 1

Views: 207

Answers (2)

rxn1d
rxn1d

Reputation: 1266

Well, you can use existing mechanism for getting configurations from Spring Environment. This is easy with @Value(${configuration_key:default_value}) annotation (assuming that you have a PropertySourcesPlaceHolderConfigurer registered somehow). Code example:

@Configuration
public class AppConfiguration {
    @Value("${http.client.endpoint:dsadas}")
    private String endPoint;
    @Value("${http.client.multiThreaded:true}")
    private boolean multiThreaded;
    @Value("${http.client.readTimeout:50000}")
    private int readTimeout;
    @Value("${http.client.connTimeout:60000}")
    private int connTimeout;
    @Value("${http.client.maxTotalConnection:40}")
    orivate int maxTotalConnection;

    @Bean
    private HttpClientConfig httpClientConfig() {
        return HttpClientConfig httpClientConfig = new HttpClientConfig
            .Builder(endPoint)
            .multiThreaded(multiThreaded)
            .readTimeout(readTimeout)
            .connTimeout(connTimeout)
            .maxTotalConnection(maxTotalConnection)
            .build();
    }
}

And configuration file (application.properties):

http.client.endpoint=value
http.client.multiThreaded=value
http.client.readTimeout=value
http.client.connTimeout=value
http.client.maxTotalConnection=value

Spring allow you to use different types of configurations, like command line arguments, system properties, configuration files, Spring Cloud Config and etc. Also configuration can be profile and environments pecific. More information at: Properties & configuration,Externalized Configuration.

Upvotes: 0

so-random-dude
so-random-dude

Reputation: 16465

In this era of stateless - ephemeral - cloud native microservices, your artifact should be environment agnostic. That means, neither keeping in code (this is the worst idea) nor keeping in the configuration file which may end up in the final artifact is a good idea. But if you are able to override the configuration from environment variable, or command line argument or external config files latter is just fine for development.

I suggest you read 12 factor App , https://content.pivotal.io/blog/beyond-the-twelve-factor-app

Upvotes: 2

Related Questions