
Externalizing configuration
Configuration can be any property that is likely to differ between environments or production deployments. Typical examples are queue and topic names, ports, URLs, connection and pool properties, and so on.
A deployable should not have configuration in it. A configuration should be injected from outside. This makes the deployable unit immutable as it goes through the various stages of the life cycle, such as Dev, QA, and UAT.
Let's assume we have to run our product service in different environments, where the URL differentiates the environment. Therefore, the small change we make in the request mapping is as follows:
@RequestMapping("/${env}product/{id}")
Product getProduct(@PathVariable("id") int id) {
We can inject this variable in various ways. Once injected, the value is not expected to change for the life of the deployment. The simplest is to pass it in the command-line argument. Bring up the Run Configurations dialog and in the Arguments, add the command-line parameter -env=dev/ as follows:

Now, Run the configuration. During startup, you will find the value substituted in the log statement as follows:
... Mapped "{[/dev/product/{id}]}" onto com.mycompany.product.Product com.mycompany.product.ProductService.getProduct(int)
The configuration can also be provided through configuration files, database, operating system environment properties, and so on.
Spring applications popularly use application.properties to store a few properties such as port numbers. Recently, YAML, which is a superset of JSON, is becoming more popular due to the hierarchical definition of the properties.
Create an application.yml file in the /product/src/main/resources folder of the application and put in the following:
server: port: 8081
This tells the product service to run at port 8081 instead of the default 8080. This concept is further extended to profiles. So, it is possible to load different profiles by loading the configuration specific to the profile.
Spring Cloud Config as a project handles this well. It uses a bootstrap.yml file to get the application started up with a name and details of the source to further load the configuration. Hence, bootstrap.yml contains the application name and config server details, and then loads the respective profile configuration.
Create a bootstrap.yml file in the resources folder of the application and put in the following:
spring: application: name: product
We will come back to these files when we discuss service registration later.