<title>2. Spring Cloud Commons: Common Abstractions</title><linkrel="stylesheet"type="text/css"href="css/manual-multipage.css"><metaname="generator"content="DocBook XSL Stylesheets V1.78.1"><linkrel="home"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="up"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="prev"href="multi__spring_cloud_context_application_context_services.html"title="1. Spring Cloud Context: Application Context Services"></head><bodybgcolor="white"text="black"link="#0000FF"vlink="#840084"alink="#0000FF"><divclass="navheader"><tablewidth="100%"summary="Navigation header"><tr><thcolspan="3"align="center">2. Spring Cloud Commons: Common Abstractions</th></tr><tr><tdwidth="20%"align="left"><aaccesskey="p"href="multi__spring_cloud_context_application_context_services.html">Prev</a> </td><thwidth="60%"align="center"> </th><tdwidth="20%"align="right"> </td></tr></table><hr></div><divclass="chapter"><divclass="titlepage"><div><div><h1class="title"><aname="_spring_cloud_commons_common_abstractions"href="#_spring_cloud_commons_common_abstractions"></a>2. Spring Cloud Commons: Common Abstractions</h1></div></div></div><p>Patterns such as service discovery, load balancing and circuit breakers lend themselves to a common abstraction layer that can be consumed by all Spring Cloud clients, independent of the implementation (e.g. discovery via Eureka or Consul).</p><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="__enablediscoveryclient"href="#__enablediscoveryclient"></a>2.1 @EnableDiscoveryClient</h2></div></div></div><p>Commons provides the <codeclass="literal">@EnableDiscoveryClient</code> annotation. This looks for implementations of the <codeclass="literal">DiscoveryClient</code> interface via <codeclass="literal">META-INF/spring.factories</code>. Implementations of Discovery Client will add a configuration class to <codeclass="literal">spring.factories</code> under the <codeclass="literal">org.springframework.cloud.client.discovery.EnableDiscoveryClient</code> key. Examples of <codeclass="literal">DiscoveryClient</code> implementations: are <aclass="link"href="http://cloud.spring.io/spring-cloud-netflix/"target="_top">Spring Cloud Netflix Eureka</a>, <aclass="link"href="http://cloud.spring.io/spring-cloud-consul/"target="_top">Spring Cloud Consul Discovery</a> and <aclass="link"href="http://cloud.spring.io/spring-cloud-zookeeper/"target="_top">Spring Cloud Zookeeper Discovery</a>.</p><p>By default, implementations of <codeclass="literal">DiscoveryClient</code> will auto-register the local Spring Boot server with the remote discovery server. This can be disabled by setting <codeclass="literal">autoRegister=false</code> in <codeclass="literal">@EnableDiscoveryClient</code>.</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>The use of <codeclass="literal">@EnableDiscoveryClient</code> is no longer required. It is enough to just have a <codeclass="literal">DiscoveryClient</code> implementation
on the classpath to cause the Spring Boot application to register with the service discovery server.</p></td></tr></table></div><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_health_indicator"href="#_health_indicator"></a>2.1.1 Health Indicator</h3></div></div></div><p>Commons creates a Spring Boot <codeclass="literal">HealthIndicator</code> that <codeclass="literal">DiscoveryClient</code> implementations can participate in by implementing <codeclass="literal">DiscoveryHealthIndicator</code>. To disable the composite <codeclass="literal">HealthIndicator</code> set <codeclass="literal">spring.cloud.discovery.client.composite-indicator.enabled=false</code>. A generic <codeclass="literal">HealthIndicator</code> based on <codeclass="literal">DiscoveryClient</code> is auto-configured (<codeclass="literal">DiscoveryClientHealthIndicator</code>). To disable it, set <codeclass="literal">spring.cloud.discovery.client.health-indicator.enabled=false</code>. To disable the description field of the <codeclass="literal">DiscoveryClientHealthIndicator</code> set <codeclass="literal">spring.cloud.discovery.client.health-indicator.include-description=false</code>, otherwise it can bubble up as the <codeclass="literal">description</code> of the rolled up <codeclass="literal">HealthIndicator</code>.</p></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_serviceregistry"href="#_serviceregistry"></a>2.2 ServiceRegistry</h2></div></div></div><p>Commons now provides a <codeclass="literal">ServiceRegistry</code> interface which provides methods like <codeclass="literal">register(Registration)</code> and <codeclass="literal">deregister(Registration)</code> which allow you to provide custom registered services. <codeclass="literal">Registration</code> is a marker interface.</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
<title>2. Spring Cloud Commons: Common Abstractions</title><linkrel="stylesheet"type="text/css"href="css/manual-multipage.css"><metaname="generator"content="DocBook XSL Stylesheets V1.78.1"><linkrel="home"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="up"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="prev"href="multi__spring_cloud_context_application_context_services.html"title="1. Spring Cloud Context: Application Context Services"></head><bodybgcolor="white"text="black"link="#0000FF"vlink="#840084"alink="#0000FF"><divclass="navheader"><tablewidth="100%"summary="Navigation header"><tr><thcolspan="3"align="center">2. Spring Cloud Commons: Common Abstractions</th></tr><tr><tdwidth="20%"align="left"><aaccesskey="p"href="multi__spring_cloud_context_application_context_services.html">Prev</a> </td><thwidth="60%"align="center"> </th><tdwidth="20%"align="right"> </td></tr></table><hr></div><divclass="chapter"><divclass="titlepage"><div><div><h1class="title"><aname="_spring_cloud_commons_common_abstractions"href="#_spring_cloud_commons_common_abstractions"></a>2. Spring Cloud Commons: Common Abstractions</h1></div></div></div><p>Patterns such as service discovery, load balancing, and circuit breakers lend themselves to a common abstraction layer that can be consumed by all Spring Cloud clients, independent of the implementation (for example, discovery with Eureka or Consul).</p><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="__enablediscoveryclient"href="#__enablediscoveryclient"></a>2.1 @EnableDiscoveryClient</h2></div></div></div><p>Spring Cloud Commons provides the <codeclass="literal">@EnableDiscoveryClient</code> annotation.
This looks for implementations of the <codeclass="literal">DiscoveryClient</code> interface with <codeclass="literal">META-INF/spring.factories</code>.
Implementations of the Discovery Client add a configuration class to <codeclass="literal">spring.factories</code> under the <codeclass="literal">org.springframework.cloud.client.discovery.EnableDiscoveryClient</code> key.
Examples of <codeclass="literal">DiscoveryClient</code> implementations include <aclass="link"href="http://cloud.spring.io/spring-cloud-netflix/"target="_top">Spring Cloud Netflix Eureka</a>, <aclass="link"href="http://cloud.spring.io/spring-cloud-consul/"target="_top">Spring Cloud Consul Discovery</a>, and <aclass="link"href="http://cloud.spring.io/spring-cloud-zookeeper/"target="_top">Spring Cloud Zookeeper Discovery</a>.</p><p>By default, implementations of <codeclass="literal">DiscoveryClient</code> auto-register the local Spring Boot server with the remote discovery server.
This behavior can be disabled by setting <codeclass="literal">autoRegister=false</code> in <codeclass="literal">@EnableDiscoveryClient</code>.</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p><codeclass="literal">@EnableDiscoveryClient</code> is no longer required.
You can put a <codeclass="literal">DiscoveryClient</code> implementation on the classpath to cause the Spring Boot application to register with the service discovery server.</p></td></tr></table></div><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_health_indicator"href="#_health_indicator"></a>2.1.1 Health Indicator</h3></div></div></div><p>Commons creates a Spring Boot <codeclass="literal">HealthIndicator</code> that <codeclass="literal">DiscoveryClient</code> implementations can participate in by implementing <codeclass="literal">DiscoveryHealthIndicator</code>.
To disable the composite <codeclass="literal">HealthIndicator</code>, set <codeclass="literal">spring.cloud.discovery.client.composite-indicator.enabled=false</code>.
A generic <codeclass="literal">HealthIndicator</code> based on <codeclass="literal">DiscoveryClient</code> is auto-configured (<codeclass="literal">DiscoveryClientHealthIndicator</code>).
To disable it, set <codeclass="literal">spring.cloud.discovery.client.health-indicator.enabled=false</code>.
To disable the description field of the <codeclass="literal">DiscoveryClientHealthIndicator</code>, set <codeclass="literal">spring.cloud.discovery.client.health-indicator.include-description=false</code>.
Otherwise, it can bubble up as the <codeclass="literal">description</code> of the rolled up <codeclass="literal">HealthIndicator</code>.</p></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_serviceregistry"href="#_serviceregistry"></a>2.2 ServiceRegistry</h2></div></div></div><p>Commons now provides a <codeclass="literal">ServiceRegistry</code> interface that provides methods such as <codeclass="literal">register(Registration)</code> and <codeclass="literal">deregister(Registration)</code>, which let you provide custom registered services.
<codeclass="literal">Registration</code> is a marker interface.</p><p>The following example shows the <codeclass="literal">ServiceRegistry</code> in use:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
@ -10,12 +20,22 @@ on the classpath to cause the Spring Boot application to register with the servi
@@ -10,12 +20,22 @@ on the classpath to cause the Spring Boot application to register with the servi
<spanxmlns:d="http://docbook.org/ns/docbook"class="hl-comment">// called via some external process, such as an event or a custom actuator endpoint</span>
<spanxmlns:d="http://docbook.org/ns/docbook"class="hl-comment">// called through some external process, such as an event or a custom actuator endpoint</span>
}</pre><p>Each <codeclass="literal">ServiceRegistry</code> implementation has its own <codeclass="literal">Registry</code> implementation.</p><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_serviceregistry_auto_registration"href="#_serviceregistry_auto_registration"></a>2.2.1 ServiceRegistry Auto-Registration</h3></div></div></div><p>By default, the <codeclass="literal">ServiceRegistry</code> implementation will auto-register the running service. To disable that behavior, there are two methods. You can set <codeclass="literal">@EnableDiscoveryClient(autoRegister=false)</code> to permanently disable auto-registration. You can also set <codeclass="literal">spring.cloud.service-registry.auto-registration.enabled=false</code> to disable the behavior via configuration.</p></div><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_service_registry_actuator_endpoint"href="#_service_registry_actuator_endpoint"></a>2.2.2 Service Registry Actuator Endpoint</h3></div></div></div><p>A <codeclass="literal">/service-registry</code> actuator endpoint is provided by Commons. This endpoint relies on a <codeclass="literal">Registration</code> bean in the Spring Application Context. Calling <codeclass="literal">/service-registry</code> via a GET will return the status of the <codeclass="literal">Registration</code>. A POST to the same endpoint with a JSON body will change the status of the current <codeclass="literal">Registration</code> to the new value. The JSON body has to include the <codeclass="literal">status</code> field with the preferred value. Please see the documentation of the <codeclass="literal">ServiceRegistry</code> implementation you are using for the allowed values for updating the status and the values returned for the status. For instance, Eureka’s supported statuses are <codeclass="literal">UP</code>, <codeclass="literal">DOWN</code>, <codeclass="literal">OUT_OF_SERVICE</code> and <codeclass="literal">UNKNOWN</code>.</p></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_spring_resttemplate_as_a_load_balancer_client"href="#_spring_resttemplate_as_a_load_balancer_client"></a>2.3 Spring RestTemplate as a Load Balancer Client</h2></div></div></div><p><codeclass="literal">RestTemplate</code> can be automatically configured to use ribbon. To create a load balanced <codeclass="literal">RestTemplate</code> create a <codeclass="literal">RestTemplate</code><codeclass="literal">@Bean</code> and use the <codeclass="literal">@LoadBalanced</code> qualifier.</p><divclass="warning"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Warning"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Warning]"src="images/warning.png"></td><thalign="left">Warning</th></tr><tr><tdalign="left"valign="top"><p>A <codeclass="literal">RestTemplate</code> bean is no longer created via auto configuration. It must be created by individual applications.</p></td></tr></table></div><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
}</pre><p>Each <codeclass="literal">ServiceRegistry</code> implementation has its own <codeclass="literal">Registry</code> implementation.</p><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_serviceregistry_auto_registration"href="#_serviceregistry_auto_registration"></a>2.2.1 ServiceRegistry Auto-Registration</h3></div></div></div><p>By default, the <codeclass="literal">ServiceRegistry</code> implementation auto-registers the running service.
To disable that behavior, you can set:
* <codeclass="literal">@EnableDiscoveryClient(autoRegister=false)</code> to permanently disable auto-registration.
* <codeclass="literal">spring.cloud.service-registry.auto-registration.enabled=false</code> to disable the behavior through configuration.</p></div><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_service_registry_actuator_endpoint"href="#_service_registry_actuator_endpoint"></a>2.2.2 Service Registry Actuator Endpoint</h3></div></div></div><p>Spring Cloud Commons provides a <codeclass="literal">/service-registry</code> actuator endpoint.
This endpoint relies on a <codeclass="literal">Registration</code> bean in the Spring Application Context.
Calling <codeclass="literal">/service-registry</code> with GET returns the status of the <codeclass="literal">Registration</code>.
Using POST to the same endpoint with a JSON body changes the status of the current <codeclass="literal">Registration</code> to the new value.
The JSON body has to include the <codeclass="literal">status</code> field with the preferred value.
Please see the documentation of the <codeclass="literal">ServiceRegistry</code> implementation you use for the allowed values when updating the status and the values returned for the status.
For instance, Eureka’s supported statuses are <codeclass="literal">UP</code>, <codeclass="literal">DOWN</code>, <codeclass="literal">OUT_OF_SERVICE</code>, and <codeclass="literal">UNKNOWN</code>.</p></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_spring_resttemplate_as_a_load_balancer_client"href="#_spring_resttemplate_as_a_load_balancer_client"></a>2.3 Spring RestTemplate as a Load Balancer Client</h2></div></div></div><p><codeclass="literal">RestTemplate</code> can be automatically configured to use ribbon.
To create a load-balanced <codeclass="literal">RestTemplate</code>, create a <codeclass="literal">RestTemplate</code><codeclass="literal">@Bean</code> and use the <codeclass="literal">@LoadBalanced</code> qualifier, as shown in the following example:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
@ -33,10 +53,11 @@ on the classpath to cause the Spring Boot application to register with the servi
@@ -33,10 +53,11 @@ on the classpath to cause the Spring Boot application to register with the servi
for details of how the <codeclass="literal">RestTemplate</code> is set up.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_spring_webclient_as_a_load_balancer_client"href="#_spring_webclient_as_a_load_balancer_client"></a>2.4 Spring WebClient as a Load Balancer Client</h2></div></div></div><p><codeclass="literal">WebClient</code> can be automatically configured to use the <codeclass="literal">LoadBalancerClient</code>. To create a load balanced <codeclass="literal">WebClient</code> create a <codeclass="literal">WebClient.Builder</code><codeclass="literal">@Bean</code> and use the <codeclass="literal">@LoadBalanced</code> qualifier.</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
}</pre><divclass="caution"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Caution"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Caution]"src="images/caution.png"></td><thalign="left">Caution</th></tr><tr><tdalign="left"valign="top"><p>A <codeclass="literal">RestTemplate</code> bean is no longer created through auto-configuration.
Individual applications must create it.</p></td></tr></table></div><p>The URI needs to use a virtual host name (that is, a service name, not a host name).
The Ribbon client is used to create a full physical address.
See <aclass="link"href="https://github.com/spring-cloud/spring-cloud-netflix/blob/master/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java"target="_top">RibbonAutoConfiguration</a> for details of how the <codeclass="literal">RestTemplate</code> is set up.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_spring_webclient_as_a_load_balancer_client"href="#_spring_webclient_as_a_load_balancer_client"></a>2.4 Spring WebClient as a Load Balancer Client</h2></div></div></div><p><codeclass="literal">WebClient</code> can be automatically configured to use the <codeclass="literal">LoadBalancerClient</code>.
To create a load-balanced <codeclass="literal">WebClient</code>, create a <codeclass="literal">WebClient.Builder</code><codeclass="literal">@Bean</code> and use the <codeclass="literal">@LoadBalanced</code> qualifier, as shown in the following example:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
@ -54,18 +75,14 @@ for details of how the <code class="literal">RestTemplate</code> is set up.</p><
@@ -54,18 +75,14 @@ for details of how the <code class="literal">RestTemplate</code> is set up.</p><
}</pre><p>The URI needs to use a virtual host name (ie. service name, not a host name).
The Ribbon client is used to create a full physical address.</p><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_retrying_failed_requests"href="#_retrying_failed_requests"></a>2.4.1 Retrying Failed Requests</h3></div></div></div><p>A load balanced <codeclass="literal">RestTemplate</code> can be configured to retry failed requests.
By default this logic is disabled, you can enable it by adding <aclass="link"href="https://github.com/spring-projects/spring-retry"target="_top">Spring Retry</a> to your application’s classpath. The load balanced <codeclass="literal">RestTemplate</code> will
honor some of the Ribbon configuration values related to retrying failed requests. If
you would like to disable the retry logic with Spring Retry on the classpath
you can set <codeclass="literal">spring.cloud.loadbalancer.retry.enabled=false</code>.
The properties you can use are <codeclass="literal">client.ribbon.MaxAutoRetries</code>,
<codeclass="literal">client.ribbon.MaxAutoRetriesNextServer</code>, and <codeclass="literal">client.ribbon.OkToRetryOnAllOperations</code>.
See the <aclass="link"href="https://github.com/Netflix/ribbon/wiki/Getting-Started#the-properties-file-sample-clientproperties"target="_top">Ribbon documentation</a>
for a description of what there properties do.</p><p>If you would like to implement a <codeclass="literal">BackOffPolicy</code> in your retries you will need to
create a bean of type <codeclass="literal">LoadBalancedBackOffPolicyFactory</code>, and return the <codeclass="literal">BackOffPolicy</code>
you would like to use for a given service.</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
}</pre><p>The URI needs to use a virtual host name (that is, a service name, not a host name).
The Ribbon client is used to create a full physical address.</p><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_retrying_failed_requests"href="#_retrying_failed_requests"></a>2.4.1 Retrying Failed Requests</h3></div></div></div><p>A load-balanced <codeclass="literal">RestTemplate</code> can be configured to retry failed requests.
By default, this logic is disabled.
You can enable it by adding <aclass="link"href="https://github.com/spring-projects/spring-retry"target="_top">Spring Retry</a> to your application’s classpath.
The load-balanced <codeclass="literal">RestTemplate</code> honors some of the Ribbon configuration values related to retrying failed requests.
You can use <codeclass="literal">client.ribbon.MaxAutoRetries</code>, <codeclass="literal">client.ribbon.MaxAutoRetriesNextServer</code>, and <codeclass="literal">client.ribbon.OkToRetryOnAllOperations</code> properties.
If you would like to disable the retry logic with Spring Retry on the classpath, you can set <codeclass="literal">spring.cloud.loadbalancer.retry.enabled=false</code>.
See the <aclass="link"href="https://github.com/Netflix/ribbon/wiki/Getting-Started#the-properties-file-sample-clientproperties"target="_top">Ribbon documentation</a> for a description of what these properties do.</p><p>If you would like to implement a <codeclass="literal">BackOffPolicy</code> in your retries, you need to create a bean of type <codeclass="literal">LoadBalancedBackOffPolicyFactory</code> and return the <codeclass="literal">BackOffPolicy</code> you would like to use for a given service, as shown in the following example:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
@ -76,10 +93,9 @@ you would like to use for a given service.</p><pre class="programlisting"><em><s
@@ -76,10 +93,9 @@ you would like to use for a given service.</p><pre class="programlisting"><em><s
}
};
}
}</pre><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p><codeclass="literal">client</code> in the above examples should be replaced with your Ribbon client’s
name.</p></td></tr></table></div><p>If you want to add one or more <codeclass="literal">RetryListener</code> to your retry you will need to
}</pre><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p><codeclass="literal">client</code> in the preceding examples should be replaced with your Ribbon client’s name.</p></td></tr></table></div><p>If you want to add one or more <codeclass="literal">RetryListener</code> implementations to your retry functionality, you need to
create a bean of type <codeclass="literal">LoadBalancedRetryListenerFactory</code> and return the <codeclass="literal">RetryListener</code> array
you would like to use for a given service.</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
you would like to use for a given service, as shown in the following example:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
@ -106,9 +122,8 @@ you would like to use for a given service.</p><pre class="programlisting"><em><s
@@ -106,9 +122,8 @@ you would like to use for a given service.</p><pre class="programlisting"><em><s
}
};
}
}</pre></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_multiple_resttemplate_objects"href="#_multiple_resttemplate_objects"></a>2.5 Multiple RestTemplate objects</h2></div></div></div><p>If you want a <codeclass="literal">RestTemplate</code> that is not load balanced, create a <codeclass="literal">RestTemplate</code>
bean and inject it as normal. To access the load balanced <codeclass="literal">RestTemplate</code> use
the <codeclass="literal">@LoadBalanced</code> qualifier when you create your <codeclass="literal">@Bean</code>.</p><divclass="important"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Important"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Important]"src="images/important.png"></td><thalign="left">Important</th></tr><tr><tdalign="left"valign="top"><p>Notice the <codeclass="literal">@Primary</code> annotation on the plain <codeclass="literal">RestTemplate</code> declaration in the example below, to disambiguate the unqualified <codeclass="literal">@Autowired</code> injection.</p></td></tr></table></div><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
}</pre></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_multiple_resttemplate_objects"href="#_multiple_resttemplate_objects"></a>2.5 Multiple RestTemplate objects</h2></div></div></div><p>If you want a <codeclass="literal">RestTemplate</code> that is not load-balanced, create a <codeclass="literal">RestTemplate</code> bean and inject it.
To access the load-balanced <codeclass="literal">RestTemplate</code>, use the <codeclass="literal">@LoadBalanced</code> qualifier when you create your <codeclass="literal">@Bean</code>, as shown in the following example:\</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
@ -139,7 +154,7 @@ the <code class="literal">@LoadBalanced</code> qualifier when you create your <c
@@ -139,7 +154,7 @@ the <code class="literal">@LoadBalanced</code> qualifier when you create your <c
}</pre><divclass="tip"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Tip"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Tip]"src="images/tip.png"></td><thalign="left">Tip</th></tr><tr><tdalign="left"valign="top"><p>If you see errors like<codeclass="literal">java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89</code> try injecting <codeclass="literal">RestOperations</code> instead or setting <codeclass="literal">spring.aop.proxyTargetClass=true</code>.</p></td></tr></table></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="loadbalanced-webclient"href="#loadbalanced-webclient"></a>2.6 Spring WebFlux WebClient as a Load Balancer Client</h2></div></div></div><p><codeclass="literal">WebClient</code> can be configured to use the <codeclass="literal">LoadBalancerClient. A `LoadBalancerExchangeFilterFunction</code> is auto-configured if spring-webflux is on the classpath.</p><preclass="programlisting"><spanxmlns:d="http://docbook.org/ns/docbook"class="hl-keyword">public</span><spanxmlns:d="http://docbook.org/ns/docbook"class="hl-keyword">class</span> MyClass {
}</pre><divclass="important"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Important"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Important]"src="images/important.png"></td><thalign="left">Important</th></tr><tr><tdalign="left"valign="top"><p>Notice the use of the <codeclass="literal">@Primary</code> annotation on the plain <codeclass="literal">RestTemplate</code> declaration in the preceding example to disambiguate the unqualified <codeclass="literal">@Autowired</code> injection.</p></td></tr></table></div><divclass="tip"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Tip"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Tip]"src="images/tip.png"></td><thalign="left">Tip</th></tr><tr><tdalign="left"valign="top"><p>If you see errors such as<codeclass="literal">java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89</code>, try injecting <codeclass="literal">RestOperations</code> or setting <codeclass="literal">spring.aop.proxyTargetClass=true</code>.</p></td></tr></table></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="loadbalanced-webclient"href="#loadbalanced-webclient"></a>2.6 Spring WebFlux WebClient as a Load Balancer Client</h2></div></div></div><p><codeclass="literal">WebClient</code> can be configured to use the <codeclass="literal">LoadBalancerClient</code>. <codeclass="literal">LoadBalancerExchangeFilterFunction</code> is auto-configured if <codeclass="literal">spring-webflux</code> is on the classpath. The following example shows how to configure a <codeclass="literal">WebClient</code> to use load balancer:</p><preclass="programlisting"><spanxmlns:d="http://docbook.org/ns/docbook"class="hl-keyword">public</span><spanxmlns:d="http://docbook.org/ns/docbook"class="hl-keyword">class</span> MyClass {
@ -152,37 +167,37 @@ the <code class="literal">@LoadBalanced</code> qualifier when you create your <c
@@ -152,37 +167,37 @@ the <code class="literal">@LoadBalanced</code> qualifier when you create your <c
}</pre><p>The URI needs to use a virtual host name (ie. service name, not a host name).
The <codeclass="literal">LoadBalancerClient</code> is used to create a full physical address.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="ignore-network-interfaces"href="#ignore-network-interfaces"></a>2.7 Ignore Network Interfaces</h2></div></div></div><p>Sometimes it is useful to ignore certain named network interfaces so they can be excluded from Service Discovery registration (eg. running in a Docker container). A list of regular expressions can be set that will cause the desired network interfaces to be ignored. The following configuration will ignore the "docker0" interface and all interfaces that start with "veth".</p><p><b>application.yml. </b>
}</pre><p>The URI needs to use a virtual host name (that is, a service name, not a host name).
The <codeclass="literal">LoadBalancerClient</code> is used to create a full physical address.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="ignore-network-interfaces"href="#ignore-network-interfaces"></a>2.7 Ignore Network Interfaces</h2></div></div></div><p>Sometimes, it is useful to ignore certain named network interfaces so that they can be excluded from Service Discovery registration (for example, when running in a Docker container).
A list of regular expressions can be set to cause the desired network interfaces to be ignored.
The following configuration ignores the <codeclass="literal">docker0</code> interface and all interfaces that start with <codeclass="literal">veth</code>:</p><p><b>application.yml. </b>
</p><preclass="screen">spring:
cloud:
inetutils:
ignoredInterfaces:
- docker0
- veth.*</pre><p>
</p><p>You can also force to use only specified network addresses using list of regular expressions:</p><p><b>application.yml. </b>
</p><p>You can also force the use of only specified network addresses by using a list of regular expressions, as shown in the following example:</p><p><b>application.yml. </b>
</p><preclass="screen">spring:
cloud:
inetutils:
preferredNetworks:
- 192.168
- 10.0</pre><p>
</p><p>You can also force to use only site local addresses. See <aclass="link"href="https://docs.oracle.com/javase/8/docs/api/java/net/Inet4Address.html#isSiteLocalAddress--"target="_top">Inet4Address.html.isSiteLocalAddress()</a> for more details what is site local address.</p><p><b>application.yml. </b>
</p><preclass="screen">spring:
</p><p>You can also force the use of only site-local addresses, as shown in the following example:
.application.yml</p><preclass="screen">spring:
cloud:
inetutils:
useOnlySiteLocalInterfaces: true</pre><p>
</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="http-clients"href="#http-clients"></a>2.8 HTTP Client Factories</h2></div></div></div><p>Spring Cloud Commons provides beans for creating both Apache HTTP clients (<codeclass="literal">ApacheHttpClientFactory</code>)
as well as OK HTTP clients (<codeclass="literal">OkHttpClientFactory</code>). The <codeclass="literal">OkHttpClientFactory</code> bean will only be created
if the OK HTTP jar is on the classpath. In addition, Spring Cloud Commons provides beans for creating
the connection managers used by both clients, <codeclass="literal">ApacheHttpClientConnectionManagerFactory</code> for the Apache
HTTP client and <codeclass="literal">OkHttpClientConnectionPoolFactory</code> for the OK HTTP client. You can provide
your own implementation of these beans if you would like to customize how the HTTP clients are created
in downstream projects. In addition, if you provide a bean of type <codeclass="literal">HttpClientBuilder</code> and/or <codeclass="literal">OkHttpClient.Builder</code>,
the default factories will use these builders as the basis for the builders returned to downstream projects.
You can also disable the creation of these beans by setting
<codeclass="literal">spring.cloud.httpclientfactories.apache.enabled</code> or <codeclass="literal">spring.cloud.httpclientfactories.ok.enabled</code> to
<codeclass="literal">false</code>.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="enabled-features"href="#enabled-features"></a>2.9 Enabled Features</h2></div></div></div><p>A <codeclass="literal">/features</code> actuator endpoint is provided by Commons. This endpoint returns features available on the classpath and if they are enabled or not. The information returned includes the feature type, name, version and vendor.</p><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_feature_types"href="#_feature_types"></a>2.9.1 Feature types</h3></div></div></div><p>There are two types of 'features': abstract and named.</p><p>Abstract features are features where an interface or abstract class is defined that an implementation creates, such as <codeclass="literal">DiscoveryClient</code>, <codeclass="literal">LoadBalancerClient</code> or <codeclass="literal">LockService</code>. The abstract class or interface is used to find a bean of that type in the context. The version displayed is <codeclass="literal">bean.getClass().getPackage().getImplementationVersion()</code>.</p><p>Named features are features that don’t have a particular class they implement, such as "Circuit Breaker", "API Gateway", "Spring Cloud Bus", etc…​ These features require a name and a bean type.</p></div><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_declaring_features"href="#_declaring_features"></a>2.9.2 Declaring features</h3></div></div></div><p>Any module can declare any number of <codeclass="literal">HasFeature</code> beans. Some examples:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Bean</span></em>
useOnlySiteLocalInterfaces: true</pre><p>See <aclass="link"href="https://docs.oracle.com/javase/8/docs/api/java/net/Inet4Address.html#isSiteLocalAddress--"target="_top">Inet4Address.html.isSiteLocalAddress()</a> for more details about what constitutes a site-local address.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="http-clients"href="#http-clients"></a>2.8 HTTP Client Factories</h2></div></div></div><p>Spring Cloud Commons provides beans for creating both Apache HTTP clients (<codeclass="literal">ApacheHttpClientFactory</code>) and OK HTTP clients (<codeclass="literal">OkHttpClientFactory</code>).
The <codeclass="literal">OkHttpClientFactory</code> bean is created only if the OK HTTP jar is on the classpath.
In addition, Spring Cloud Commons provides beans for creating the connection managers used by both clients: <codeclass="literal">ApacheHttpClientConnectionManagerFactory</code> for the Apache HTTP client and <codeclass="literal">OkHttpClientConnectionPoolFactory</code> for the OK HTTP client.
If you would like to customize how the HTTP clients are created in downstream projects, you can provide your own implementation of these beans.
In addition, if you provide a bean of type <codeclass="literal">HttpClientBuilder</code> or <codeclass="literal">OkHttpClient.Builder</code>, the default factories use these builders as the basis for the builders returned to downstream projects.
You can also disable the creation of these beans by setting <codeclass="literal">spring.cloud.httpclientfactories.apache.enabled</code> or <codeclass="literal">spring.cloud.httpclientfactories.ok.enabled</code> to <codeclass="literal">false</code>.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="enabled-features"href="#enabled-features"></a>2.9 Enabled Features</h2></div></div></div><p>Spring Cloud Commons provides a <codeclass="literal">/features</code> actuator endpoint.
This endpoint returns features available on the classpath and whether they are enabled.
The information returned includes the feature type, name, version, and vendor.</p><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_feature_types"href="#_feature_types"></a>2.9.1 Feature types</h3></div></div></div><p>There are two types of 'features': abstract and named.</p><p>Abstract features are features where an interface or abstract class is defined and that an implementation the creates, such as <codeclass="literal">DiscoveryClient</code>, <codeclass="literal">LoadBalancerClient</code>, or <codeclass="literal">LockService</code>.
The abstract class or interface is used to find a bean of that type in the context.
The version displayed is <codeclass="literal">bean.getClass().getPackage().getImplementationVersion()</code>.</p><p>Named features are features that do not have a particular class they implement, such as "Circuit Breaker", "API Gateway", "Spring Cloud Bus", and others. These features require a name and a bean type.</p></div><divclass="section"><divclass="titlepage"><div><div><h3class="title"><aname="_declaring_features"href="#_declaring_features"></a>2.9.2 Declaring features</h3></div></div></div><p>Any module can declare any number of <codeclass="literal">HasFeature</code> beans, as shown in the following examples:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Bean</span></em>
<title>1. Spring Cloud Context: Application Context Services</title><linkrel="stylesheet"type="text/css"href="css/manual-multipage.css"><metaname="generator"content="DocBook XSL Stylesheets V1.78.1"><linkrel="home"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="up"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="prev"href="multi_pr01.html"title=""><linkrel="next"href="multi__spring_cloud_commons_common_abstractions.html"title="2. Spring Cloud Commons: Common Abstractions"></head><bodybgcolor="white"text="black"link="#0000FF"vlink="#840084"alink="#0000FF"><divclass="navheader"><tablewidth="100%"summary="Navigation header"><tr><thcolspan="3"align="center">1. Spring Cloud Context: Application Context Services</th></tr><tr><tdwidth="20%"align="left"><aaccesskey="p"href="multi_pr01.html">Prev</a> </td><thwidth="60%"align="center"> </th><tdwidth="20%"align="right"> <aaccesskey="n"href="multi__spring_cloud_commons_common_abstractions.html">Next</a></td></tr></table><hr></div><divclass="chapter"><divclass="titlepage"><div><div><h1class="title"><aname="_spring_cloud_context_application_context_services"href="#_spring_cloud_context_application_context_services"></a>1. Spring Cloud Context: Application Context Services</h1></div></div></div><p>Spring Boot has an opinionated view of how to build an application
with Spring: for instance it has conventional locations for common
configuration file, and endpoints for common management and monitoring
tasks. Spring Cloud builds on top of that and adds a few features that
probably all components in a system would use or occasionally need.</p><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_the_bootstrap_application_context"href="#_the_bootstrap_application_context"></a>1.1 The Bootstrap Application Context</h2></div></div></div><p>A Spring Cloud application operates by creating a "bootstrap"
context, which is a parent context for the main application. Out of
the box it is responsible for loading configuration properties from
the external sources, and also decrypting properties in the local
external configuration files. The two contexts share an <codeclass="literal">Environment</code>
which is the source of external properties for any Spring
application. Bootstrap properties are added with high precedence, so
they cannot be overridden by local configuration, by default.</p><p>The bootstrap context uses a different convention for locating
external configuration than the main application context, so instead
of <codeclass="literal">application.yml</code> (or <codeclass="literal">.properties</code>) you use <codeclass="literal">bootstrap.yml</code>,
keeping the external configuration for bootstrap and main context
<title>1. Spring Cloud Context: Application Context Services</title><linkrel="stylesheet"type="text/css"href="css/manual-multipage.css"><metaname="generator"content="DocBook XSL Stylesheets V1.78.1"><linkrel="home"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="up"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="prev"href="multi_pr01.html"title=""><linkrel="next"href="multi__spring_cloud_commons_common_abstractions.html"title="2. Spring Cloud Commons: Common Abstractions"></head><bodybgcolor="white"text="black"link="#0000FF"vlink="#840084"alink="#0000FF"><divclass="navheader"><tablewidth="100%"summary="Navigation header"><tr><thcolspan="3"align="center">1. Spring Cloud Context: Application Context Services</th></tr><tr><tdwidth="20%"align="left"><aaccesskey="p"href="multi_pr01.html">Prev</a> </td><thwidth="60%"align="center"> </th><tdwidth="20%"align="right"> <aaccesskey="n"href="multi__spring_cloud_commons_common_abstractions.html">Next</a></td></tr></table><hr></div><divclass="chapter"><divclass="titlepage"><div><div><h1class="title"><aname="_spring_cloud_context_application_context_services"href="#_spring_cloud_context_application_context_services"></a>1. Spring Cloud Context: Application Context Services</h1></div></div></div><p>Spring Boot has an opinionated view of how to build an application with Spring.
For instance, it has conventional locations for common configuration files and has endpoints for common management and monitoring tasks.
Spring Cloud builds on top of that and adds a few features that probably all components in a system would use or occasionally need.</p><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_the_bootstrap_application_context"href="#_the_bootstrap_application_context"></a>1.1 The Bootstrap Application Context</h2></div></div></div><p>A Spring Cloud application operates by creating a “bootstrap” context, which is a parent context for the main application.
It is responsible for loading configuration properties from the external sources and for decrypting properties in the local external configuration files.
The two contexts share an <codeclass="literal">Environment</code>, which is the source of external properties for any Spring application.
By default, bootstrap properties are added with high precedence, so they cannot be overridden by local configuration.</p><p>The bootstrap context uses a different convention for locating external configuration than the main application context.
Instead of <codeclass="literal">application.yml</code> (or <codeclass="literal">.properties</code>), you can use <codeclass="literal">bootstrap.yml</code>, keeping the external configuration for bootstrap and main context
nicely separate.
The following listing shows an example:</p><p><b>bootstrap.yml. </b>
</p><p>It is a good idea to set the <codeclass="literal">spring.application.name</code> (in
<codeclass="literal">bootstrap.yml</code> or <codeclass="literal">application.yml</code>) if your application needs any
application-specific configuration from the server.</p><p>You can disable the bootstrap process completely by setting
<codeclass="literal">spring.cloud.bootstrap.enabled=false</code> (e.g. in System properties).</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_application_context_hierarchies"href="#_application_context_hierarchies"></a>1.2 Application Context Hierarchies</h2></div></div></div><p>If you build an application context from <codeclass="literal">SpringApplication</code> or
<codeclass="literal">SpringApplicationBuilder</code>, then the Bootstrap context is added as a
parent to that context. It is a feature of Spring that child contexts
inherit property sources and profiles from their parent, so the "main"
application context will contain additional property sources, compared
to building the same context without Spring Cloud Config. The
additional property sources are:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem">"bootstrap": an optional <codeclass="literal">CompositePropertySource</code> appears with high
priority if any <codeclass="literal">PropertySourceLocators</code> are found in the Bootstrap
context, and they have non-empty properties. An example would be
properties from the Spring Cloud Config Server. See
<aclass="link"href="multi__spring_cloud_context_application_context_services.html#customizing-bootstrap-property-sources"title="1.6 Customizing the Bootstrap Property Sources">below</a> for instructions
on how to customize the contents of this property source.</li><liclass="listitem">"applicationConfig: [classpath:bootstrap.yml]" (and friends if
Spring profiles are active). If you have a <codeclass="literal">bootstrap.yml</code> (or
properties) then those properties are used to configure the Bootstrap
context, and then they get added to the child context when its parent
is set. They have lower precedence than the <codeclass="literal">application.yml</code> (or
properties) and any other property sources that are added to the child
as a normal part of the process of creating a Spring Boot
application. See <aclass="link"href="multi__spring_cloud_context_application_context_services.html#customizing-bootstrap-properties"title="1.3 Changing the Location of Bootstrap Properties">below</a> for
instructions on how to customize the contents of these property
sources.</li></ul></div><p>Because of the ordering rules of property sources the "bootstrap"
entries take precedence, but note that these do not contain any data
from <codeclass="literal">bootstrap.yml</code>, which has very low precedence, but can be used
to set defaults.</p><p>You can extend the context hierarchy by simply setting the parent
context of any <codeclass="literal">ApplicationContext</code> you create, e.g. using its own
interface, or with the <codeclass="literal">SpringApplicationBuilder</code> convenience methods
(<codeclass="literal">parent()</code>, <codeclass="literal">child()</code> and <codeclass="literal">sibling()</code>). The bootstrap context will be
the parent of the most senior ancestor that you create yourself.
Every context in the hierarchy will have its own "bootstrap" property
source (possibly empty) to avoid promoting values inadvertently from
parents down to their descendants. Every context in the hierarchy can
also (in principle) have a different <codeclass="literal">spring.application.name</code> and
hence a different remote property source if there is a Config
Server. Normal Spring application context behaviour rules apply to
property resolution: properties from a child context override those in
the parent, by name and also by property source name (if the child has
a property source with the same name as the parent, the one from the
parent is not included in the child).</p><p>Note that the <codeclass="literal">SpringApplicationBuilder</code> allows you to share an
<codeclass="literal">Environment</code> amongst the whole hierarchy, but that is not the
default. Thus, sibling contexts in particular do not need to have the
same profiles or property sources, even though they will share common
things with their parent.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="customizing-bootstrap-properties"href="#customizing-bootstrap-properties"></a>1.3 Changing the Location of Bootstrap Properties</h2></div></div></div><p>The <codeclass="literal">bootstrap.yml</code> (or <codeclass="literal">.properties</code>) location can be specified using
<codeclass="literal">spring.cloud.bootstrap.name</code> (default "bootstrap") or
<codeclass="literal">spring.cloud.bootstrap.location</code> (default empty), e.g. in System
properties. Those properties behave like the <codeclass="literal">spring.config.*</code>
variants with the same name, in fact they are used to set up the
bootstrap <codeclass="literal">ApplicationContext</code> by setting those properties in its
<codeclass="literal">Environment</code>. If there is an active profile (from
<codeclass="literal">spring.profiles.active</code> or through the <codeclass="literal">Environment</code> API in the
context you are building) then properties in that profile will be
loaded as well, just like in a regular Spring Boot app, e.g. from
<codeclass="literal">bootstrap-development.properties</code> for a "development" profile.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="overriding-bootstrap-properties"href="#overriding-bootstrap-properties"></a>1.4 Overriding the Values of Remote Properties</h2></div></div></div><p>The property sources that are added to you application by the
bootstrap context are often "remote" (e.g. from a Config Server), and
by default they cannot be overridden locally, except on the command
line. If you want to allow your applications to override the remote
properties with their own System properties or config files, the
remote property source has to grant it permission by setting
<codeclass="literal">spring.cloud.config.allowOverride=true</code> (it doesn’t work to set this
locally). Once that flag is set there are some finer grained settings
to control the location of the remote properties in relation to System
properties and the application’s local configuration:
<codeclass="literal">spring.cloud.config.overrideNone=true</code> to override with any local
property source, and
<codeclass="literal">spring.cloud.config.overrideSystemProperties=false</code> if only System
properties and env vars should override the remote settings, but not
the local config files.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_customizing_the_bootstrap_configuration"href="#_customizing_the_bootstrap_configuration"></a>1.5 Customizing the Bootstrap Configuration</h2></div></div></div><p>The bootstrap context can be trained to do anything you like by adding
entries to <codeclass="literal">/META-INF/spring.factories</code> under the key
<codeclass="literal">org.springframework.cloud.bootstrap.BootstrapConfiguration</code>. This is
a comma-separated list of Spring <codeclass="literal">@Configuration</code> classes which will
be used to create the context. Any beans that you want to be available
to the main application context for autowiring can be created here,
and also there is a special contract for <codeclass="literal">@Beans</code> of type
<codeclass="literal">ApplicationContextInitializer</code>. Classes can be marked with an <codeclass="literal">@Order</code>
if you want to control the startup sequence (the default order is
"last").</p><divclass="warning"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Warning"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Warning]"src="images/warning.png"></td><thalign="left">Warning</th></tr><tr><tdalign="left"valign="top"><p>Be careful when adding custom <codeclass="literal">BootstrapConfiguration</code> that the
classes you add are not <codeclass="literal">@ComponentScanned</code> by mistake into your
"main" application context, where they might not be needed.
Use a separate package name for boot configuration classes that is
not already covered by your <codeclass="literal">@ComponentScan</code> or <codeclass="literal">@SpringBootApplication</code>
annotated configuration classes.</p></td></tr></table></div><p>The bootstrap process ends by injecting initializers into the main
<codeclass="literal">SpringApplication</code> instance (i.e. the normal Spring Boot startup
sequence, whether it is running as a standalone app or deployed in an
application server). First a bootstrap context is created from the
classes found in <codeclass="literal">spring.factories</code> and then all <codeclass="literal">@Beans</code> of type
<codeclass="literal">ApplicationContextInitializer</code> are added to the main
<codeclass="literal">SpringApplication</code> before it is started.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="customizing-bootstrap-property-sources"href="#customizing-bootstrap-property-sources"></a>1.6 Customizing the Bootstrap Property Sources</h2></div></div></div><p>The default property source for external configuration added by the
bootstrap process is the Config Server, but you can add additional
sources by adding beans of type <codeclass="literal">PropertySourceLocator</code> to the
bootstrap context (via <codeclass="literal">spring.factories</code>). You could use this to
insert additional properties from a different server, or from a
database, for instance.</p><p>As an example, consider the following trivial custom locator:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
</p><p>If your application needs any application-specific configuration from the server, it is a good idea to set the <codeclass="literal">spring.application.name</code> (in <codeclass="literal">bootstrap.yml</code> or <codeclass="literal">application.yml</code>).</p><p>You can disable the bootstrap process completely by setting <codeclass="literal">spring.cloud.bootstrap.enabled=false</code> (for example, in system properties).</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_application_context_hierarchies"href="#_application_context_hierarchies"></a>1.2 Application Context Hierarchies</h2></div></div></div><p>If you build an application context from <codeclass="literal">SpringApplication</code> or <codeclass="literal">SpringApplicationBuilder</code>, then the Bootstrap context is added as a parent to that context.
It is a feature of Spring that child contexts inherit property sources and profiles from their parent, so the “main” application context contains additional property sources, compared to building the same context without Spring Cloud Config.
The additional property sources are:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem">“bootstrap”: If any <codeclass="literal">PropertySourceLocators</code> are found in the Bootstrap context and if they have non-empty properties, an optional <codeclass="literal">CompositePropertySource</code> appears with high priority.
An example would be properties from the Spring Cloud Config Server.
See “<aclass="xref"href="multi__spring_cloud_context_application_context_services.html#customizing-bootstrap-property-sources"title="1.6 Customizing the Bootstrap Property Sources">Section 1.6, “Customizing the Bootstrap Property Sources”</a>” for instructions on how to customize the contents of this property source.</li><liclass="listitem">“applicationConfig: [classpath:bootstrap.yml]” (and related files if Spring profiles are active): If you have a <codeclass="literal">bootstrap.yml</code> (or <codeclass="literal">.properties</code>), those properties are used to configure the Bootstrap context.
Then they get added to the child context when its parent is set.
They have lower precedence than the <codeclass="literal">application.yml</code> (or <codeclass="literal">.properties</code>) and any other property sources that are added to the child as a normal part of the process of creating a Spring Boot application.
See “<aclass="xref"href="multi__spring_cloud_context_application_context_services.html#customizing-bootstrap-properties"title="1.3 Changing the Location of Bootstrap Properties">Section 1.3, “Changing the Location of Bootstrap Properties”</a>” for instructions on how to customize the contents of these property sources.</li></ul></div><p>Because of the ordering rules of property sources, the “bootstrap” entries take precedence.
However, note that these do not contain any data from <codeclass="literal">bootstrap.yml</code>, which has very low precedence but can be used to set defaults.</p><p>You can extend the context hierarchy by setting the parent context of any <codeclass="literal">ApplicationContext</code> you create — for example, by using its own interface or with the <codeclass="literal">SpringApplicationBuilder</code> convenience methods (<codeclass="literal">parent()</code>, <codeclass="literal">child()</code> and <codeclass="literal">sibling()</code>).
The bootstrap context is the parent of the most senior ancestor that you create yourself.
Every context in the hierarchy has its own “bootstrap” (possibly empty) property source to avoid promoting values inadvertently from parents down to their descendants.
If there is a Config Server, every context in the hierarchy can also (in principle) have a different <codeclass="literal">spring.application.name</code> and, hence, a different remote property source.
Normal Spring application context behavior rules apply to property resolution: properties from a child context override those in
the parent, by name and also by property source name.
(If the child has a property source with the same name as the parent, the value from the parent is not included in the child).</p><p>Note that the <codeclass="literal">SpringApplicationBuilder</code> lets you share an <codeclass="literal">Environment</code> amongst the whole hierarchy, but that is not the default.
Thus, sibling contexts, in particular, do not need to have the same profiles or property sources, even though they may share common values with their parent.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="customizing-bootstrap-properties"href="#customizing-bootstrap-properties"></a>1.3 Changing the Location of Bootstrap Properties</h2></div></div></div><p>The <codeclass="literal">bootstrap.yml</code> (or <codeclass="literal">.properties</code>) location can be specified by setting <codeclass="literal">spring.cloud.bootstrap.name</code> (default: <codeclass="literal">bootstrap</code>) or <codeclass="literal">spring.cloud.bootstrap.location</code> (default: empty) — for example, in System properties.
Those properties behave like the <codeclass="literal">spring.config.*</code> variants with the same name.
In fact, they are used to set up the bootstrap <codeclass="literal">ApplicationContext</code> by setting those properties in its <codeclass="literal">Environment</code>.
If there is an active profile (from <codeclass="literal">spring.profiles.active</code> or through the <codeclass="literal">Environment</code> API in the
context you are building), properties in that profile get loaded as well, the same as in a regular Spring Boot app — for example, from <codeclass="literal">bootstrap-development.properties</code> for a <codeclass="literal">development</code> profile.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="overriding-bootstrap-properties"href="#overriding-bootstrap-properties"></a>1.4 Overriding the Values of Remote Properties</h2></div></div></div><p>The property sources that are added to your application by the bootstrap context are often “remote” (from example, from Spring Cloud Config Server).
By default, they cannot be overridden locally, except on the command line.
If you want to let your applications override the remote properties with their own System properties or config files, the remote property source has to grant it permission by setting <codeclass="literal">spring.cloud.config.allowOverride=true</code> (it does not work to set this locally).
Once that flag is set, two finer-grained settings control the location of the remote properties in relation to system properties and the application’s local configuration:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem"><codeclass="literal">spring.cloud.config.overrideNone=true</code>: Override from any local property source.</li><liclass="listitem"><codeclass="literal">spring.cloud.config.overrideSystemProperties=false</code>: Only system properties and environment variables (but not the local config files) should override the remote settings.</li></ul></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_customizing_the_bootstrap_configuration"href="#_customizing_the_bootstrap_configuration"></a>1.5 Customizing the Bootstrap Configuration</h2></div></div></div><p>The bootstrap context can be set to do anything you like by adding entries to <codeclass="literal">/META-INF/spring.factories</code> under a key named <codeclass="literal">org.springframework.cloud.bootstrap.BootstrapConfiguration</code>.
This holds a comma-separated list of Spring <codeclass="literal">@Configuration</code> classes that are used to create the context.
Any beans that you want to be available to the main application context for autowiring can be created here.
There is a special contract for <codeclass="literal">@Beans</code> of type <codeclass="literal">ApplicationContextInitializer</code>.
If you want to control the startup sequence, classes can be marked with an <codeclass="literal">@Order</code> annotation (the default order is <codeclass="literal">last</code>).</p><divclass="warning"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Warning"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Warning]"src="images/warning.png"></td><thalign="left">Warning</th></tr><tr><tdalign="left"valign="top"><p>When adding custom <codeclass="literal">BootstrapConfiguration</code>, be careful that the classes you add are not <codeclass="literal">@ComponentScanned</code> by mistake into your “main” application context, where they might not be needed.
Use a separate package name for boot configuration classes and make sure that name is not already covered by your <codeclass="literal">@ComponentScan</code> or <codeclass="literal">@SpringBootApplication</code> annotated configuration classes.</p></td></tr></table></div><p>The bootstrap process ends by injecting initializers into the main <codeclass="literal">SpringApplication</code> instance (which is the normal Spring Boot startup sequence, whether it is running as a standalone application or deployed in an application server).
First, a bootstrap context is created from the classes found in <codeclass="literal">spring.factories</code>.
Then, all <codeclass="literal">@Beans</code> of type <codeclass="literal">ApplicationContextInitializer</code> are added to the main <codeclass="literal">SpringApplication</code> before it is started.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="customizing-bootstrap-property-sources"href="#customizing-bootstrap-property-sources"></a>1.6 Customizing the Bootstrap Property Sources</h2></div></div></div><p>The default property source for external configuration added by the bootstrap process is the Spring Cloud Config Server, but you can add additional sources by adding beans of type <codeclass="literal">PropertySourceLocator</code> to the bootstrap context (through <codeclass="literal">spring.factories</code>).
For instance, you can insert additional properties from a different server or from a database.</p><p>As an example, consider the following custom locator:</p><preclass="programlisting"><em><spanclass="hl-annotation"style="color: gray">@Configuration</span></em>
@ -124,67 +54,27 @@ database, for instance.</p><p>As an example, consider the following trivial cust
@@ -124,67 +54,27 @@ database, for instance.</p><p>As an example, consider the following trivial cust
Collections.<String, Object>singletonMap(<spanxmlns:d="http://docbook.org/ns/docbook"class="hl-string">"property.from.sample.custom.source"</span>, <spanxmlns:d="http://docbook.org/ns/docbook"class="hl-string">"worked as intended"</span>));
}
}</pre><p>The <codeclass="literal">Environment</code> that is passed in is the one for the
<codeclass="literal">ApplicationContext</code> about to be created, i.e. the one that we are
supplying additional property sources for. It will already have its
normal Spring Boot-provided property sources, so you can use those to
locate a property source specific to this <codeclass="literal">Environment</code> (e.g. by
keying it on the <codeclass="literal">spring.application.name</code>, as is done in the default
Config Server property source locator).</p><p>If you create a jar with this class in it and then add a
<codeclass="literal">META-INF/spring.factories</code> containing:</p><preclass="screen">org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator</pre><p>then the "customProperty" <codeclass="literal">PropertySource</code> will show up in any
application that includes that jar on its classpath.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_environment_changes"href="#_environment_changes"></a>1.7 Environment Changes</h2></div></div></div><p>The application will listen for an <codeclass="literal">EnvironmentChangeEvent</code> and react
to the change in a couple of standard ways (additional
<codeclass="literal">ApplicationListeners</code> can be added as <codeclass="literal">@Beans</code> by the user in the
normal way). When an <codeclass="literal">EnvironmentChangeEvent</code> is observed it will
have a list of key values that have changed, and the application will
use those to:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem">Re-bind any <codeclass="literal">@ConfigurationProperties</code> beans in the context</li><liclass="listitem">Set the logger levels for any properties in <codeclass="literal">logging.level.*</code></li></ul></div><p>Note that the Config Client does not by default poll for changes in
the <codeclass="literal">Environment</code>, and generally we would not recommend that approach
for detecting changes (although you could set it up with a
<codeclass="literal">@Scheduled</code> annotation). If you have a scaled-out client application
then it is better to broadcast the <codeclass="literal">EnvironmentChangeEvent</code> to all
the instances instead of having them polling for changes (e.g. using
the <aclass="link"href="https://github.com/spring-cloud/spring-cloud-bus"target="_top">Spring Cloud
Bus</a>).</p><p>The <codeclass="literal">EnvironmentChangeEvent</code> covers a large class of refresh use
cases, as long as you can actually make a change to the <codeclass="literal">Environment</code>
and publish the event (those APIs are public and part of core
Spring). You can verify the changes are bound to
<codeclass="literal">@ConfigurationProperties</code> beans by visiting the <codeclass="literal">/configprops</code>
endpoint (normal Spring Boot Actuator feature). For instance a
<codeclass="literal">DataSource</code> can have its <codeclass="literal">maxPoolSize</code> changed at runtime (the
default <codeclass="literal">DataSource</code> created by Spring Boot is an
<codeclass="literal">@ConfigurationProperties</code> bean) and grow capacity
dynamically. Re-binding <codeclass="literal">@ConfigurationProperties</code> does not cover
another large class of use cases, where you need more control over the
refresh, and where you need a change to be atomic over the whole
<codeclass="literal">ApplicationContext</code>. To address those concerns we have
<codeclass="literal">@RefreshScope</code>.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_refresh_scope"href="#_refresh_scope"></a>1.8 Refresh Scope</h2></div></div></div><p>A Spring <codeclass="literal">@Bean</code> that is marked as <codeclass="literal">@RefreshScope</code> will get special
treatment when there is a configuration change. This addresses the
problem of stateful beans that only get their configuration injected
when they are initialized. For instance if a <codeclass="literal">DataSource</code> has open
connections when the database URL is changed via the <codeclass="literal">Environment</code>, we
probably want the holders of those connections to be able to complete
what they are doing. Then the next time someone borrows a connection
from the pool he gets one with the new URL.</p><p>Refresh scope beans are lazy proxies that initialize when they are
used (i.e. when a method is called), and the scope acts as a cache of
initialized values. To force a bean to re-initialize on the next
method call you just need to invalidate its cache entry.</p><p>The <codeclass="literal">RefreshScope</code> is a bean in the context and it has a public method
<codeclass="literal">refreshAll()</code> to refresh all beans in the scope by clearing the
target cache. This functionality is exposed in the
<codeclass="literal">/refresh</code> endpoint (over HTTP or JMX). There is also a <codeclass="literal">refresh(String)</code> method to refresh an
individual bean by name.</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p><codeclass="literal">@RefreshScope</code> works (technically) on an <codeclass="literal">@Configuration</code>
class, but it might lead to surprising behaviour: e.g. it does <spanclass="strong"><strong>not</strong></span>
mean that all the <codeclass="literal">@Beans</code> defined in that class are themselves
<codeclass="literal">@RefreshScope</code>. Specifically, anything that depends on those beans
cannot rely on them being updated when a refresh is initiated, unless
it is itself in <codeclass="literal">@RefreshScope</code> (in which it will be rebuilt on a
refresh and its dependencies re-injected, at which point they will be
re-initialized from the refreshed <codeclass="literal">@Configuration</code>).</p></td></tr></table></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_encryption_and_decryption"href="#_encryption_and_decryption"></a>1.9 Encryption and Decryption</h2></div></div></div><p>Spring Cloud has an <codeclass="literal">Environment</code> pre-processor for decrypting
property values locally. It follows the same rules as the Config
Server, and has the same external configuration via <codeclass="literal">encrypt.*</code>. Thus
you can use encrypted values in the form <codeclass="literal">{cipher}*</code> and as long as
there is a valid key then they will be decrypted before the main
application context gets the <codeclass="literal">Environment</code>. To use the encryption
features in an application you need to include Spring Security RSA in
your classpath (Maven co-ordinates
"org.springframework.security:spring-security-rsa") and you also need
the full strength JCE extensions in your JVM.</p><p>If you are getting an exception due to "Illegal key size" and you are using Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. See the following links for more information:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html"target="_top">Java 6 JCE</a></li><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html"target="_top">Java 7 JCE</a></li><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html"target="_top">Java 8 JCE</a></li></ul></div><p>Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using).</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_endpoints"href="#_endpoints"></a>1.10 Endpoints</h2></div></div></div><p>For a Spring Boot Actuator application there are some additional management endpoints:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem">POST to <codeclass="literal">/env</code> to update the <codeclass="literal">Environment</code> and rebind <codeclass="literal">@ConfigurationProperties</code> and log levels</li><liclass="listitem"><codeclass="literal">/refresh</code> for re-loading the boot strap context and refreshing the <codeclass="literal">@RefreshScope</code> beans</li><liclass="listitem"><codeclass="literal">/restart</code> for closing the <codeclass="literal">ApplicationContext</code> and restarting it (disabled by default)</li><liclass="listitem"><codeclass="literal">/pause</code> and <codeclass="literal">/resume</code> for calling the <codeclass="literal">Lifecycle</code> methods (<codeclass="literal">stop()</code> and <codeclass="literal">start()</code> on the <codeclass="literal">ApplicationContext</code>)</li></ul></div></div></div><divclass="navfooter"><hr><tablewidth="100%"summary="Navigation footer"><tr><tdwidth="40%"align="left"><aaccesskey="p"href="multi_pr01.html">Prev</a> </td><tdwidth="20%"align="center"> </td><tdwidth="40%"align="right"> <aaccesskey="n"href="multi__spring_cloud_commons_common_abstractions.html">Next</a></td></tr><tr><tdwidth="40%"align="left"valign="top"> </td><tdwidth="20%"align="center"><aaccesskey="h"href="multi_spring-cloud-commons.html">Home</a></td><tdwidth="40%"align="right"valign="top"> 2. Spring Cloud Commons: Common Abstractions</td></tr></table></div></body></html>
}</pre><p>The <codeclass="literal">Environment</code> that is passed in is the one for the <codeclass="literal">ApplicationContext</code> about to be created — in other words, the one for which we supply additional property sources for.
It already has its normal Spring Boot-provided property sources, so you can use those to locate a property source specific to this <codeclass="literal">Environment</code> (for example, by keying it on <codeclass="literal">spring.application.name</code>, as is done in the default Spring Cloud Config Server property source locator).</p><p>If you create a jar with this class in it and then add a <codeclass="literal">META-INF/spring.factories</code> containing the following, the <codeclass="literal">customProperty</code><codeclass="literal">PropertySource</code> appears in any application that includes that jar on its classpath:</p><preclass="screen">org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator</pre></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_environment_changes"href="#_environment_changes"></a>1.7 Environment Changes</h2></div></div></div><p>The application listens for an <codeclass="literal">EnvironmentChangeEvent</code> and reacts to the change in a couple of standard ways (additional <codeclass="literal">ApplicationListeners</code> can be added as <codeclass="literal">@Beans</code> by the user in the normal way).
When an <codeclass="literal">EnvironmentChangeEvent</code> is observed, it has a list of key values that have changed, and the application uses those to:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem">Re-bind any <codeclass="literal">@ConfigurationProperties</code> beans in the context</li><liclass="listitem">Set the logger levels for any properties in <codeclass="literal">logging.level.*</code></li></ul></div><p>Note that the Config Client does not, by default, poll for changes in the <codeclass="literal">Environment</code>.
Generally, we would not recommend that approach for detecting changes (although you could set it up with a
If you have a scaled-out client application, it is better to broadcast the <codeclass="literal">EnvironmentChangeEvent</code> to all the instances instead of having them polling for changes (for example, by using the <aclass="link"href="https://github.com/spring-cloud/spring-cloud-bus"target="_top">Spring Cloud Bus</a>).</p><p>The <codeclass="literal">EnvironmentChangeEvent</code> covers a large class of refresh use cases, as long as you can actually make a change to the <codeclass="literal">Environment</code> and publish the event.
Note that those APIs are public and part of core Spring).
You can verify that the changes are bound to <codeclass="literal">@ConfigurationProperties</code> beans by visiting the <codeclass="literal">/configprops</code> endpoint (a normal Spring Boot Actuator feature).
For instance, a <codeclass="literal">DataSource</code> can have its <codeclass="literal">maxPoolSize</code> changed at runtime (the default <codeclass="literal">DataSource</code> created by Spring Boot is an <codeclass="literal">@ConfigurationProperties</code> bean) and grow capacity dynamically.
Re-binding <codeclass="literal">@ConfigurationProperties</code> does not cover another large class of use cases, where you need more control over the refresh and where you need a change to be atomic over the whole <codeclass="literal">ApplicationContext</code>.
To address those concerns, we have <codeclass="literal">@RefreshScope</code>.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_refresh_scope"href="#_refresh_scope"></a>1.8 Refresh Scope</h2></div></div></div><p>When there is a configuration change, a Spring <codeclass="literal">@Bean</code> that is marked as <codeclass="literal">@RefreshScope</code> gets special treatment.
This feature addresses the problem of stateful beans that only get their configuration injected when they are initialized.
For instance, if a <codeclass="literal">DataSource</code> has open connections when the database URL is changed via the <codeclass="literal">Environment</code>, you probably want the holders of those connections to be able to complete what they are doing.
Then, the next time something borrows a connection from the pool, it gets one with the new URL.</p><p>Refresh scope beans are lazy proxies that initialize when they are used (that is, when a method is called), and the scope acts as a cache of initialized values.
To force a bean to re-initialize on the next method call, you must invalidate its cache entry.</p><p>The <codeclass="literal">RefreshScope</code> is a bean in the context and has a public <codeclass="literal">refreshAll()</code> method to refresh all beans in the scope by clearing the target cache.
The <codeclass="literal">/refresh</code> endpoint exposes this functionality (over HTTP or JMX).
To refresh an individual bean by name, there is also a <codeclass="literal">refresh(String)</code> method.</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p><codeclass="literal">@RefreshScope</code> works (technically) on an <codeclass="literal">@Configuration</code> class, but it might lead to surprising behavior.
For example, it does <spanclass="strong"><strong>not</strong></span> mean that all the <codeclass="literal">@Beans</code> defined in that class are themselves in <codeclass="literal">@RefreshScope</code>.
Specifically, anything that depends on those beans cannot rely on them being updated when a refresh is initiated, unless it is itself in <codeclass="literal">@RefreshScope</code>.
In that case, it is rebuilt on a refresh and its dependencies are re-injected. At that point, they are re-initialized from the refreshed <codeclass="literal">@Configuration</code>).</p></td></tr></table></div></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_encryption_and_decryption"href="#_encryption_and_decryption"></a>1.9 Encryption and Decryption</h2></div></div></div><p>Spring Cloud has an <codeclass="literal">Environment</code> pre-processor for decrypting property values locally.
It follows the same rules as the Config Server and has the same external configuration through <codeclass="literal">encrypt.*</code>.
Thus, you can use encrypted values in the form of <codeclass="literal">{cipher}*</code> and, as long as there is a valid key, they are decrypted before the main application context gets the <codeclass="literal">Environment</code> settings.
To use the encryption features in an application, you need to include Spring Security RSA in your classpath (Maven co-ordinates: "org.springframework.security:spring-security-rsa"), and you also need the full strength JCE extensions in your JVM.</p><p>If you get an exception due to "Illegal key size" and you use Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files.
See the following links for more information:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html"target="_top">Java 6 JCE</a></li><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html"target="_top">Java 7 JCE</a></li><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html"target="_top">Java 8 JCE</a></li></ul></div><p>Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.</p></div><divclass="section"><divclass="titlepage"><div><div><h2class="title"style="clear: both"><aname="_endpoints"href="#_endpoints"></a>1.10 Endpoints</h2></div></div></div><p>For a Spring Boot Actuator application, some additional management endpoints are available. You can use:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem"><codeclass="literal">POST</code> to <codeclass="literal">/actuator/env</code> to update the <codeclass="literal">Environment</code> and rebind <codeclass="literal">@ConfigurationProperties</code> and log levels.</li><liclass="listitem"><codeclass="literal">/actuator/refresh</code> to re-load the boot strap context and refresh the <codeclass="literal">@RefreshScope</code> beans.</li><liclass="listitem"><codeclass="literal">/actuator/restart</code> to close the <codeclass="literal">ApplicationContext</code> and restart it (disabled by default).</li><liclass="listitem"><codeclass="literal">/actuator/pause</code> and <codeclass="literal">/actuator/resume</code> for calling the <codeclass="literal">Lifecycle</code> methods (<codeclass="literal">stop()</code> and <codeclass="literal">start()</code> on the <codeclass="literal">ApplicationContext</code>).</li></ul></div></div></div><divclass="navfooter"><hr><tablewidth="100%"summary="Navigation footer"><tr><tdwidth="40%"align="left"><aaccesskey="p"href="multi_pr01.html">Prev</a> </td><tdwidth="20%"align="center"> </td><tdwidth="40%"align="right"> <aaccesskey="n"href="multi__spring_cloud_commons_common_abstractions.html">Next</a></td></tr><tr><tdwidth="40%"align="left"valign="top"> </td><tdwidth="20%"align="center"><aaccesskey="h"href="multi_spring-cloud-commons.html">Home</a></td><tdwidth="40%"align="right"valign="top"> 2. Spring Cloud Commons: Common Abstractions</td></tr></table></div></body></html>
<title></title><linkrel="stylesheet"type="text/css"href="css/manual-multipage.css"><metaname="generator"content="DocBook XSL Stylesheets V1.78.1"><linkrel="home"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="up"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="prev"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="next"href="multi__spring_cloud_context_application_context_services.html"title="1. Spring Cloud Context: Application Context Services"></head><bodybgcolor="white"text="black"link="#0000FF"vlink="#840084"alink="#0000FF"><divclass="navheader"><tablewidth="100%"summary="Navigation header"><tr><thcolspan="3"align="center"></th></tr><tr><tdwidth="20%"align="left"><aaccesskey="p"href="multi_spring-cloud-commons.html">Prev</a> </td><thwidth="60%"align="center"> </th><tdwidth="20%"align="right"> <aaccesskey="n"href="multi__spring_cloud_context_application_context_services.html">Next</a></td></tr></table><hr></div><divclass="preface"><divclass="titlepage"><div><div><h1class="title"><aname="d0e9"href="#d0e9"></a></h1></div></div></div><p><aclass="link"href="http://pivotal.io/platform-as-a-service/migrating-to-cloud-native-application-architectures-ebook"target="_top">Cloud Native</a> is a style of application development that encourages easy adoption of best practices in the areas of continuous delivery and value-driven development. A related discipline is that of building <aclass="link"href="http://12factor.net/"target="_top">12-factor Apps</a> in which development practices are aligned with delivery and operations goals, for instance by using declarative programming and management and monitoring. Spring Cloud facilitates these styles of development in a number of specific ways and the starting point is a set of features that all components in a distributed system either need or need easy access to when required.</p><p>Many of those features are covered by <aclass="link"href="http://projects.spring.io/spring-boot"target="_top">Spring Boot</a>, which we build on in Spring Cloud. Some more are delivered by Spring Cloud as two libraries: Spring Cloud Context and Spring Cloud Commons. Spring Cloud Context provides utilities and special services for the <codeclass="literal">ApplicationContext</code> of a Spring Cloud application (bootstrap context, encryption, refresh scope and environment endpoints). Spring Cloud Commons is a set of abstractions and common classes used in different Spring Cloud implementations (eg. Spring Cloud Netflix vs. Spring Cloud Consul).</p><p>If you are getting an exception due to "Illegal key size" and you are using Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. See the following links for more information:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html"target="_top">Java 6 JCE</a></li><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html"target="_top">Java 7 JCE</a></li><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html"target="_top">Java 8 JCE</a></li></ul></div><p>Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using).</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>Spring Cloud is released under the non-restrictive Apache 2.0 license. If you would like to contribute to this section of the documentation or if you find an error, please find the source code and issue trackers in the project at <aclass="link"href="https://github.com/spring-cloud/spring-cloud-commons/tree/master/docs/src/main/asciidoc"target="_top">github</a>.</p></td></tr></table></div></div><divclass="navfooter"><hr><tablewidth="100%"summary="Navigation footer"><tr><tdwidth="40%"align="left"><aaccesskey="p"href="multi_spring-cloud-commons.html">Prev</a> </td><tdwidth="20%"align="center"> </td><tdwidth="40%"align="right"> <aaccesskey="n"href="multi__spring_cloud_context_application_context_services.html">Next</a></td></tr><tr><tdwidth="40%"align="left"valign="top">Cloud Native Applications </td><tdwidth="20%"align="center"><aaccesskey="h"href="multi_spring-cloud-commons.html">Home</a></td><tdwidth="40%"align="right"valign="top"> 1. Spring Cloud Context: Application Context Services</td></tr></table></div></body></html>
<title></title><linkrel="stylesheet"type="text/css"href="css/manual-multipage.css"><metaname="generator"content="DocBook XSL Stylesheets V1.78.1"><linkrel="home"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="up"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="prev"href="multi_spring-cloud-commons.html"title="Cloud Native Applications"><linkrel="next"href="multi__spring_cloud_context_application_context_services.html"title="1. Spring Cloud Context: Application Context Services"></head><bodybgcolor="white"text="black"link="#0000FF"vlink="#840084"alink="#0000FF"><divclass="navheader"><tablewidth="100%"summary="Navigation header"><tr><thcolspan="3"align="center"></th></tr><tr><tdwidth="20%"align="left"><aaccesskey="p"href="multi_spring-cloud-commons.html">Prev</a> </td><thwidth="60%"align="center"> </th><tdwidth="20%"align="right"> <aaccesskey="n"href="multi__spring_cloud_context_application_context_services.html">Next</a></td></tr></table><hr></div><divclass="preface"><divclass="titlepage"><div><div><h1class="title"><aname="d0e9"href="#d0e9"></a></h1></div></div></div><p><aclass="link"href="http://pivotal.io/platform-as-a-service/migrating-to-cloud-native-application-architectures-ebook"target="_top">Cloud Native</a> is a style of application development that encourages easy adoption of best practices in the areas of continuous delivery and value-driven development.
A related discipline is that of building <aclass="link"href="http://12factor.net/"target="_top">12-factor Applications</a>, in which development practices are aligned with delivery and operations goals — for instance, by using declarative programming and management and monitoring.
Spring Cloud facilitates these styles of development in a number of specific ways.
The starting point is a set of features to which all components in a distributed system need easy access.</p><p>Many of those features are covered by <aclass="link"href="http://projects.spring.io/spring-boot"target="_top">Spring Boot</a>, on which Spring Cloud builds. Some more features are delivered by Spring Cloud as two libraries: Spring Cloud Context and Spring Cloud Commons.
Spring Cloud Context provides utilities and special services for the <codeclass="literal">ApplicationContext</code> of a Spring Cloud application (bootstrap context, encryption, refresh scope, and environment endpoints). Spring Cloud Commons is a set of abstractions and common classes used in different Spring Cloud implementations (such as Spring Cloud Netflix and Spring Cloud Consul).</p><p>If you get an exception due to "Illegal key size" and you use Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files.
See the following links for more information:</p><divclass="itemizedlist"><ulclass="itemizedlist"style="list-style-type: disc; "><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html"target="_top">Java 6 JCE</a></li><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html"target="_top">Java 7 JCE</a></li><liclass="listitem"><aclass="link"href="http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html"target="_top">Java 8 JCE</a></li></ul></div><p>Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.</p><divclass="note"style="margin-left: 0.5in; margin-right: 0.5in;"><tableborder="0"summary="Note"><tr><tdrowspan="2"align="center"valign="top"width="25"><imgalt="[Note]"src="images/note.png"></td><thalign="left">Note</th></tr><tr><tdalign="left"valign="top"><p>Spring Cloud is released under the non-restrictive Apache 2.0 license.
If you would like to contribute to this section of the documentation or if you find an error, you can find the source code and issue trackers for the project at <aclass="link"href="https://github.com/spring-cloud/spring-cloud-commons/tree/master/docs/src/main/asciidoc"target="_top">github</a>.</p></td></tr></table></div></div><divclass="navfooter"><hr><tablewidth="100%"summary="Navigation footer"><tr><tdwidth="40%"align="left"><aaccesskey="p"href="multi_spring-cloud-commons.html">Prev</a> </td><tdwidth="20%"align="center"> </td><tdwidth="40%"align="right"> <aaccesskey="n"href="multi__spring_cloud_context_application_context_services.html">Next</a></td></tr><tr><tdwidth="40%"align="left"valign="top">Cloud Native Applications </td><tdwidth="20%"align="center"><aaccesskey="h"href="multi_spring-cloud-commons.html">Home</a></td><tdwidth="40%"align="right"valign="top"> 1. Spring Cloud Context: Application Context Services</td></tr></table></div></body></html>
<simpara><linkxl:href="http://pivotal.io/platform-as-a-service/migrating-to-cloud-native-application-architectures-ebook">Cloud Native</link> is a style of application development that encourages easy adoption of best practices in the areas of continuous delivery and value-driven development. A related discipline is that of building <linkxl:href="http://12factor.net/">12-factor Apps</link> in which development practices are aligned with delivery and operations goals, for instance by using declarative programming and management and monitoring. Spring Cloud facilitates these styles of development in a number of specific ways and the starting point is a set of features that all components in a distributed system either need or need easy access to when required.</simpara>
<simpara>Many of those features are covered by <linkxl:href="http://projects.spring.io/spring-boot">Spring Boot</link>, which we build on in Spring Cloud. Some more are delivered by Spring Cloud as two libraries: Spring Cloud Context and Spring Cloud Commons. Spring Cloud Context provides utilities and special services for the <literal>ApplicationContext</literal> of a Spring Cloud application (bootstrap context, encryption, refresh scope and environment endpoints). Spring Cloud Commons is a set of abstractions and common classes used in different Spring Cloud implementations (eg. Spring Cloud Netflix vs. Spring Cloud Consul).</simpara>
<simpara>If you are getting an exception due to "Illegal key size" and you are using Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. See the following links for more information:</simpara>
<simpara><linkxl:href="http://pivotal.io/platform-as-a-service/migrating-to-cloud-native-application-architectures-ebook">Cloud Native</link> is a style of application development that encourages easy adoption of best practices in the areas of continuous delivery and value-driven development.
A related discipline is that of building <linkxl:href="http://12factor.net/">12-factor Applications</link>, in which development practices are aligned with delivery and operations goals — for instance, by using declarative programming and management and monitoring.
Spring Cloud facilitates these styles of development in a number of specific ways.
The starting point is a set of features to which all components in a distributed system need easy access.</simpara>
<simpara>Many of those features are covered by <linkxl:href="http://projects.spring.io/spring-boot">Spring Boot</link>, on which Spring Cloud builds. Some more features are delivered by Spring Cloud as two libraries: Spring Cloud Context and Spring Cloud Commons.
Spring Cloud Context provides utilities and special services for the <literal>ApplicationContext</literal> of a Spring Cloud application (bootstrap context, encryption, refresh scope, and environment endpoints). Spring Cloud Commons is a set of abstractions and common classes used in different Spring Cloud implementations (such as Spring Cloud Netflix and Spring Cloud Consul).</simpara>
<simpara>If you get an exception due to "Illegal key size" and you use Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files.
See the following links for more information:</simpara>
<simpara>Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using).</simpara>
<simpara>Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.</simpara>
<note>
<simpara>Spring Cloud is released under the non-restrictive Apache 2.0 license. If you would like to contribute to this section of the documentation or if you find an error, please find the source code and issue trackers in the project at <linkxl:href="https://github.com/spring-cloud/spring-cloud-commons/tree/master/docs/src/main/asciidoc">github</link>.</simpara>
<simpara>Spring Cloud is released under the non-restrictive Apache 2.0 license.
If you would like to contribute to this section of the documentation or if you find an error, you can find the source code and issue trackers for the project at <linkxl:href="https://github.com/spring-cloud/spring-cloud-commons/tree/master/docs/src/main/asciidoc">github</link>.</simpara>
<simpara>A Spring Cloud application operates by creating a "bootstrap"
context, which is a parent context for the main application. Out of
the box it is responsible for loading configuration properties from
the external sources, and also decrypting properties in the local
external configuration files. The two contexts share an <literal>Environment</literal>
which is the source of external properties for any Spring
application. Bootstrap properties are added with high precedence, so
they cannot be overridden by local configuration, by default.</simpara>
<simpara>The bootstrap context uses a different convention for locating
external configuration than the main application context, so instead
of <literal>application.yml</literal> (or <literal>.properties</literal>) you use <literal>bootstrap.yml</literal>,
keeping the external configuration for bootstrap and main context
nicely separate. Example:</simpara>
<simpara>A Spring Cloud application operates by creating a “bootstrap” context, which is a parent context for the main application.
It is responsible for loading configuration properties from the external sources and for decrypting properties in the local external configuration files.
The two contexts share an <literal>Environment</literal>, which is the source of external properties for any Spring application.
By default, bootstrap properties are added with high precedence, so they cannot be overridden by local configuration.</simpara>
<simpara>The bootstrap context uses a different convention for locating external configuration than the main application context.
Instead of <literal>application.yml</literal> (or <literal>.properties</literal>), you can use <literal>bootstrap.yml</literal>, keeping the external configuration for bootstrap and main context
<simpara>It is a good idea to set the <literal>spring.application.name</literal> (in
<literal>bootstrap.yml</literal> or <literal>application.yml</literal>) if your application needs any
application-specific configuration from the server.</simpara>
<simpara>You can disable the bootstrap process completely by setting
<literal>spring.cloud.bootstrap.enabled=false</literal> (e.g. in System properties).</simpara>
<simpara>If your application needs any application-specific configuration from the server, it is a good idea to set the <literal>spring.application.name</literal> (in <literal>bootstrap.yml</literal> or <literal>application.yml</literal>).</simpara>
<simpara>You can disable the bootstrap process completely by setting <literal>spring.cloud.bootstrap.enabled=false</literal> (for example, in system properties).</simpara>
<simpara>If you build an application context from <literal>SpringApplication</literal> or
<literal>SpringApplicationBuilder</literal>, then the Bootstrap context is added as a
parent to that context. It is a feature of Spring that child contexts
inherit property sources and profiles from their parent, so the "main"
application context will contain additional property sources, compared
to building the same context without Spring Cloud Config. The
additional property sources are:</simpara>
<simpara>If you build an application context from <literal>SpringApplication</literal> or <literal>SpringApplicationBuilder</literal>, then the Bootstrap context is added as a parent to that context.
It is a feature of Spring that child contexts inherit property sources and profiles from their parent, so the “main” application context contains additional property sources, compared to building the same context without Spring Cloud Config.
The additional property sources are:</simpara>
<itemizedlist>
<listitem>
<simpara>"bootstrap": an optional <literal>CompositePropertySource</literal> appears with high
priority if any <literal>PropertySourceLocators</literal> are found in the Bootstrap
context, and they have non-empty properties. An example would be
properties from the Spring Cloud Config Server. See
<linkxl:href="#customizing-bootstrap-property-sources">below</link> for instructions
on how to customize the contents of this property source.</simpara>
<simpara>“bootstrap”: If any <literal>PropertySourceLocators</literal> are found in the Bootstrap context and if they have non-empty properties, an optional <literal>CompositePropertySource</literal> appears with high priority.
An example would be properties from the Spring Cloud Config Server.
See “<xreflinkend="customizing-bootstrap-property-sources"/>” for instructions on how to customize the contents of this property source.</simpara>
</listitem>
<listitem>
<simpara>"applicationConfig: [classpath:bootstrap.yml]" (and friends if
Spring profiles are active). If you have a <literal>bootstrap.yml</literal> (or
properties) then those properties are used to configure the Bootstrap
context, and then they get added to the child context when its parent
is set. They have lower precedence than the <literal>application.yml</literal> (or
properties) and any other property sources that are added to the child
as a normal part of the process of creating a Spring Boot
application. See <linkxl:href="#customizing-bootstrap-properties">below</link> for
instructions on how to customize the contents of these property
sources.</simpara>
<simpara>“applicationConfig: [classpath:bootstrap.yml]” (and related files if Spring profiles are active): If you have a <literal>bootstrap.yml</literal> (or <literal>.properties</literal>), those properties are used to configure the Bootstrap context.
Then they get added to the child context when its parent is set.
They have lower precedence than the <literal>application.yml</literal> (or <literal>.properties</literal>) and any other property sources that are added to the child as a normal part of the process of creating a Spring Boot application.
See “<xreflinkend="customizing-bootstrap-properties"/>” for instructions on how to customize the contents of these property sources.</simpara>
</listitem>
</itemizedlist>
<simpara>Because of the ordering rules of property sources the "bootstrap"
entries take precedence, but note that these do not contain any data
from <literal>bootstrap.yml</literal>, which has very low precedence, but can be used
to set defaults.</simpara>
<simpara>You can extend the context hierarchy by simply setting the parent
context of any <literal>ApplicationContext</literal> you create, e.g. using its own
interface, or with the <literal>SpringApplicationBuilder</literal> convenience methods
(<literal>parent()</literal>, <literal>child()</literal> and <literal>sibling()</literal>). The bootstrap context will be
the parent of the most senior ancestor that you create yourself.
Every context in the hierarchy will have its own "bootstrap" property
source (possibly empty) to avoid promoting values inadvertently from
parents down to their descendants. Every context in the hierarchy can
also (in principle) have a different <literal>spring.application.name</literal> and
hence a different remote property source if there is a Config
Server. Normal Spring application context behaviour rules apply to
property resolution: properties from a child context override those in
the parent, by name and also by property source name (if the child has
a property source with the same name as the parent, the one from the
parent is not included in the child).</simpara>
<simpara>Note that the <literal>SpringApplicationBuilder</literal> allows you to share an
<literal>Environment</literal> amongst the whole hierarchy, but that is not the
default. Thus, sibling contexts in particular do not need to have the
same profiles or property sources, even though they will share common
things with their parent.</simpara>
<simpara>Because of the ordering rules of property sources, the “bootstrap” entries take precedence.
However, note that these do not contain any data from <literal>bootstrap.yml</literal>, which has very low precedence but can be used to set defaults.</simpara>
<simpara>You can extend the context hierarchy by setting the parent context of any <literal>ApplicationContext</literal> you create — for example, by using its own interface or with the <literal>SpringApplicationBuilder</literal> convenience methods (<literal>parent()</literal>, <literal>child()</literal> and <literal>sibling()</literal>).
The bootstrap context is the parent of the most senior ancestor that you create yourself.
Every context in the hierarchy has its own “bootstrap” (possibly empty) property source to avoid promoting values inadvertently from parents down to their descendants.
If there is a Config Server, every context in the hierarchy can also (in principle) have a different <literal>spring.application.name</literal> and, hence, a different remote property source.
Normal Spring application context behavior rules apply to property resolution: properties from a child context override those in
the parent, by name and also by property source name.
(If the child has a property source with the same name as the parent, the value from the parent is not included in the child).</simpara>
<simpara>Note that the <literal>SpringApplicationBuilder</literal> lets you share an <literal>Environment</literal> amongst the whole hierarchy, but that is not the default.
Thus, sibling contexts, in particular, do not need to have the same profiles or property sources, even though they may share common values with their parent.</simpara>
<title>Changing the Location of Bootstrap Properties</title>
<simpara>The <literal>bootstrap.yml</literal> (or <literal>.properties</literal>) location can be specified using
<literal>spring.cloud.bootstrap.name</literal> (default "bootstrap") or
<literal>spring.cloud.bootstrap.location</literal> (default empty), e.g. in System
properties. Those properties behave like the <literal>spring.config.*</literal>
variants with the same name, in fact they are used to set up the
bootstrap <literal>ApplicationContext</literal> by setting those properties in its
<literal>Environment</literal>. If there is an active profile (from
<literal>spring.profiles.active</literal> or through the <literal>Environment</literal> API in the
context you are building) then properties in that profile will be
loaded as well, just like in a regular Spring Boot app, e.g. from
<literal>bootstrap-development.properties</literal> for a "development" profile.</simpara>
<simpara>The <literal>bootstrap.yml</literal> (or <literal>.properties</literal>) location can be specified by setting <literal>spring.cloud.bootstrap.name</literal> (default: <literal>bootstrap</literal>) or <literal>spring.cloud.bootstrap.location</literal> (default: empty) — for example, in System properties.
Those properties behave like the <literal>spring.config.*</literal> variants with the same name.
In fact, they are used to set up the bootstrap <literal>ApplicationContext</literal> by setting those properties in its <literal>Environment</literal>.
If there is an active profile (from <literal>spring.profiles.active</literal> or through the <literal>Environment</literal> API in the
context you are building), properties in that profile get loaded as well, the same as in a regular Spring Boot app — for example, from <literal>bootstrap-development.properties</literal> for a <literal>development</literal> profile.</simpara>
</section>
<sectionxml:id="overriding-bootstrap-properties">
<title>Overriding the Values of Remote Properties</title>
<simpara>The property sources that are added to you application by the
bootstrap context are often "remote" (e.g. from a Config Server), and
by default they cannot be overridden locally, except on the command
line. If you want to allow your applications to override the remote
properties with their own System properties or config files, the
remote property source has to grant it permission by setting
<literal>spring.cloud.config.allowOverride=true</literal> (it doesn’t work to set this
locally). Once that flag is set there are some finer grained settings
to control the location of the remote properties in relation to System
properties and the application’s local configuration:
<literal>spring.cloud.config.overrideNone=true</literal> to override with any local
property source, and
<literal>spring.cloud.config.overrideSystemProperties=false</literal> if only System
properties and env vars should override the remote settings, but not
the local config files.</simpara>
<simpara>The property sources that are added to your application by the bootstrap context are often “remote” (from example, from Spring Cloud Config Server).
By default, they cannot be overridden locally, except on the command line.
If you want to let your applications override the remote properties with their own System properties or config files, the remote property source has to grant it permission by setting <literal>spring.cloud.config.allowOverride=true</literal> (it does not work to set this locally).
Once that flag is set, two finer-grained settings control the location of the remote properties in relation to system properties and the application’s local configuration:</simpara>
<itemizedlist>
<listitem>
<simpara><literal>spring.cloud.config.overrideNone=true</literal>: Override from any local property source.</simpara>
</listitem>
<listitem>
<simpara><literal>spring.cloud.config.overrideSystemProperties=false</literal>: Only system properties and environment variables (but not the local config files) should override the remote settings.</simpara>
<title>Customizing the Bootstrap Configuration</title>
<simpara>The bootstrap context can be trained to do anything you like by adding
entries to <literal>/META-INF/spring.factories</literal> under the key
<literal>org.springframework.cloud.bootstrap.BootstrapConfiguration</literal>. This is
a comma-separated list of Spring <literal>@Configuration</literal> classes which will
be used to create the context. Any beans that you want to be available
to the main application context for autowiring can be created here,
and also there is a special contract for <literal>@Beans</literal> of type
<literal>ApplicationContextInitializer</literal>. Classes can be marked with an <literal>@Order</literal>
if you want to control the startup sequence (the default order is
"last").</simpara>
<simpara>The bootstrap context can be set to do anything you like by adding entries to <literal>/META-INF/spring.factories</literal> under a key named <literal>org.springframework.cloud.bootstrap.BootstrapConfiguration</literal>.
This holds a comma-separated list of Spring <literal>@Configuration</literal> classes that are used to create the context.
Any beans that you want to be available to the main application context for autowiring can be created here.
There is a special contract for <literal>@Beans</literal> of type <literal>ApplicationContextInitializer</literal>.
If you want to control the startup sequence, classes can be marked with an <literal>@Order</literal> annotation (the default order is <literal>last</literal>).</simpara>
<warning>
<simpara>Be careful when adding custom <literal>BootstrapConfiguration</literal> that the
classes you add are not <literal>@ComponentScanned</literal> by mistake into your
"main" application context, where they might not be needed.
Use a separate package name for boot configuration classes that is
not already covered by your <literal>@ComponentScan</literal> or <literal>@SpringBootApplication</literal>
annotated configuration classes.</simpara>
<simpara>When adding custom <literal>BootstrapConfiguration</literal>, be careful that the classes you add are not <literal>@ComponentScanned</literal> by mistake into your “main” application context, where they might not be needed.
Use a separate package name for boot configuration classes and make sure that name is not already covered by your <literal>@ComponentScan</literal> or <literal>@SpringBootApplication</literal> annotated configuration classes.</simpara>
</warning>
<simpara>The bootstrap process ends by injecting initializers into the main
<literal>SpringApplication</literal> instance (i.e. the normal Spring Boot startup
sequence, whether it is running as a standalone app or deployed in an
application server). First a bootstrap context is created from the
classes found in <literal>spring.factories</literal> and then all <literal>@Beans</literal> of type
<literal>ApplicationContextInitializer</literal> are added to the main
<literal>SpringApplication</literal> before it is started.</simpara>
<simpara>The bootstrap process ends by injecting initializers into the main <literal>SpringApplication</literal> instance (which is the normal Spring Boot startup sequence, whether it is running as a standalone application or deployed in an application server).
First, a bootstrap context is created from the classes found in <literal>spring.factories</literal>.
Then, all <literal>@Beans</literal> of type <literal>ApplicationContextInitializer</literal> are added to the main <literal>SpringApplication</literal> before it is started.</simpara>
<title>Customizing the Bootstrap Property Sources</title>
<simpara>The default property source for external configuration added by the
bootstrap process is the Config Server, but you can add additional
sources by adding beans of type <literal>PropertySourceLocator</literal> to the
bootstrap context (via <literal>spring.factories</literal>). You could use this to
insert additional properties from a different server, or from a
database, for instance.</simpara>
<simpara>As an example, consider the following trivial custom locator:</simpara>
<simpara>The default property source for external configuration added by the bootstrap process is the Spring Cloud Config Server, but you can add additional sources by adding beans of type <literal>PropertySourceLocator</literal> to the bootstrap context (through <literal>spring.factories</literal>).
For instance, you can insert additional properties from a different server or from a database.</simpara>
<simpara>As an example, consider the following custom locator:</simpara>
public class CustomPropertySourceLocator implements PropertySourceLocator {
@ -201,27 +145,15 @@ public class CustomPropertySourceLocator implements PropertySourceLocator {
@@ -201,27 +145,15 @@ public class CustomPropertySourceLocator implements PropertySourceLocator {
}
}</programlisting>
<simpara>The <literal>Environment</literal> that is passed in is the one for the
<literal>ApplicationContext</literal> about to be created, i.e. the one that we are
supplying additional property sources for. It will already have its
normal Spring Boot-provided property sources, so you can use those to
locate a property source specific to this <literal>Environment</literal> (e.g. by
keying it on the <literal>spring.application.name</literal>, as is done in the default
Config Server property source locator).</simpara>
<simpara>If you create a jar with this class in it and then add a
<simpara>The <literal>Environment</literal> that is passed in is the one for the <literal>ApplicationContext</literal> about to be created — in other words, the one for which we supply additional property sources for.
It already has its normal Spring Boot-provided property sources, so you can use those to locate a property source specific to this <literal>Environment</literal> (for example, by keying it on <literal>spring.application.name</literal>, as is done in the default Spring Cloud Config Server property source locator).</simpara>
<simpara>If you create a jar with this class in it and then add a <literal>META-INF/spring.factories</literal> containing the following, the <literal>customProperty</literal><literal>PropertySource</literal> appears in any application that includes that jar on its classpath:</simpara>
<simpara>then the "customProperty" <literal>PropertySource</literal> will show up in any
application that includes that jar on its classpath.</simpara>
</section>
<sectionxml:id="_environment_changes">
<title>Environment Changes</title>
<simpara>The application will listen for an <literal>EnvironmentChangeEvent</literal> and react
to the change in a couple of standard ways (additional
<literal>ApplicationListeners</literal> can be added as <literal>@Beans</literal> by the user in the
normal way). When an <literal>EnvironmentChangeEvent</literal> is observed it will
have a list of key values that have changed, and the application will
use those to:</simpara>
<simpara>The application listens for an <literal>EnvironmentChangeEvent</literal> and reacts to the change in a couple of standard ways (additional <literal>ApplicationListeners</literal> can be added as <literal>@Beans</literal> by the user in the normal way).
When an <literal>EnvironmentChangeEvent</literal> is observed, it has a list of key values that have changed, and the application uses those to:</simpara>
<itemizedlist>
<listitem>
<simpara>Re-bind any <literal>@ConfigurationProperties</literal> beans in the context</simpara>
@ -230,72 +162,43 @@ use those to:</simpara>
@@ -230,72 +162,43 @@ use those to:</simpara>
<simpara>Set the logger levels for any properties in <literal>logging.level.*</literal></simpara>
</listitem>
</itemizedlist>
<simpara>Note that the Config Client does not by default poll for changes in
the <literal>Environment</literal>, and generally we would not recommend that approach
for detecting changes (although you could set it up with a
<literal>@Scheduled</literal> annotation). If you have a scaled-out client application
then it is better to broadcast the <literal>EnvironmentChangeEvent</literal> to all
the instances instead of having them polling for changes (e.g. using
the <linkxl:href="https://github.com/spring-cloud/spring-cloud-bus">Spring Cloud
Bus</link>).</simpara>
<simpara>The <literal>EnvironmentChangeEvent</literal> covers a large class of refresh use
cases, as long as you can actually make a change to the <literal>Environment</literal>
and publish the event (those APIs are public and part of core
Spring). You can verify the changes are bound to
<literal>@ConfigurationProperties</literal> beans by visiting the <literal>/configprops</literal>
endpoint (normal Spring Boot Actuator feature). For instance a
<literal>DataSource</literal> can have its <literal>maxPoolSize</literal> changed at runtime (the
default <literal>DataSource</literal> created by Spring Boot is an
<literal>@ConfigurationProperties</literal> bean) and grow capacity
dynamically. Re-binding <literal>@ConfigurationProperties</literal> does not cover
another large class of use cases, where you need more control over the
refresh, and where you need a change to be atomic over the whole
<literal>ApplicationContext</literal>. To address those concerns we have
<literal>@RefreshScope</literal>.</simpara>
<simpara>Note that the Config Client does not, by default, poll for changes in the <literal>Environment</literal>.
Generally, we would not recommend that approach for detecting changes (although you could set it up with a
<literal>@Scheduled</literal> annotation).
If you have a scaled-out client application, it is better to broadcast the <literal>EnvironmentChangeEvent</literal> to all the instances instead of having them polling for changes (for example, by using the <linkxl:href="https://github.com/spring-cloud/spring-cloud-bus">Spring Cloud Bus</link>).</simpara>
<simpara>The <literal>EnvironmentChangeEvent</literal> covers a large class of refresh use cases, as long as you can actually make a change to the <literal>Environment</literal> and publish the event.
Note that those APIs are public and part of core Spring).
You can verify that the changes are bound to <literal>@ConfigurationProperties</literal> beans by visiting the <literal>/configprops</literal> endpoint (a normal Spring Boot Actuator feature).
For instance, a <literal>DataSource</literal> can have its <literal>maxPoolSize</literal> changed at runtime (the default <literal>DataSource</literal> created by Spring Boot is an <literal>@ConfigurationProperties</literal> bean) and grow capacity dynamically.
Re-binding <literal>@ConfigurationProperties</literal> does not cover another large class of use cases, where you need more control over the refresh and where you need a change to be atomic over the whole <literal>ApplicationContext</literal>.
To address those concerns, we have <literal>@RefreshScope</literal>.</simpara>
</section>
<sectionxml:id="_refresh_scope">
<title>Refresh Scope</title>
<simpara>A Spring <literal>@Bean</literal> that is marked as <literal>@RefreshScope</literal> will get special
treatment when there is a configuration change. This addresses the
problem of stateful beans that only get their configuration injected
when they are initialized. For instance if a <literal>DataSource</literal> has open
connections when the database URL is changed via the <literal>Environment</literal>, we
probably want the holders of those connections to be able to complete
what they are doing. Then the next time someone borrows a connection
from the pool he gets one with the new URL.</simpara>
<simpara>Refresh scope beans are lazy proxies that initialize when they are
used (i.e. when a method is called), and the scope acts as a cache of
initialized values. To force a bean to re-initialize on the next
method call you just need to invalidate its cache entry.</simpara>
<simpara>The <literal>RefreshScope</literal> is a bean in the context and it has a public method
<literal>refreshAll()</literal> to refresh all beans in the scope by clearing the
target cache. This functionality is exposed in the
<literal>/refresh</literal> endpoint (over HTTP or JMX). There is also a <literal>refresh(String)</literal> method to refresh an
individual bean by name.</simpara>
<simpara>When there is a configuration change, a Spring <literal>@Bean</literal> that is marked as <literal>@RefreshScope</literal> gets special treatment.
This feature addresses the problem of stateful beans that only get their configuration injected when they are initialized.
For instance, if a <literal>DataSource</literal> has open connections when the database URL is changed via the <literal>Environment</literal>, you probably want the holders of those connections to be able to complete what they are doing.
Then, the next time something borrows a connection from the pool, it gets one with the new URL.</simpara>
<simpara>Refresh scope beans are lazy proxies that initialize when they are used (that is, when a method is called), and the scope acts as a cache of initialized values.
To force a bean to re-initialize on the next method call, you must invalidate its cache entry.</simpara>
<simpara>The <literal>RefreshScope</literal> is a bean in the context and has a public <literal>refreshAll()</literal> method to refresh all beans in the scope by clearing the target cache.
The <literal>/refresh</literal> endpoint exposes this functionality (over HTTP or JMX).
To refresh an individual bean by name, there is also a <literal>refresh(String)</literal> method.</simpara>
<note>
<simpara><literal>@RefreshScope</literal> works (technically) on an <literal>@Configuration</literal>
class, but it might lead to surprising behaviour: e.g. it does <emphasisrole="strong">not</emphasis>
mean that all the <literal>@Beans</literal> defined in that class are themselves
<literal>@RefreshScope</literal>. Specifically, anything that depends on those beans
cannot rely on them being updated when a refresh is initiated, unless
it is itself in <literal>@RefreshScope</literal> (in which it will be rebuilt on a
refresh and its dependencies re-injected, at which point they will be
re-initialized from the refreshed <literal>@Configuration</literal>).</simpara>
<simpara><literal>@RefreshScope</literal> works (technically) on an <literal>@Configuration</literal> class, but it might lead to surprising behavior.
For example, it does <emphasisrole="strong">not</emphasis> mean that all the <literal>@Beans</literal> defined in that class are themselves in <literal>@RefreshScope</literal>.
Specifically, anything that depends on those beans cannot rely on them being updated when a refresh is initiated, unless it is itself in <literal>@RefreshScope</literal>.
In that case, it is rebuilt on a refresh and its dependencies are re-injected. At that point, they are re-initialized from the refreshed <literal>@Configuration</literal>).</simpara>
</note>
</section>
<sectionxml:id="_encryption_and_decryption">
<title>Encryption and Decryption</title>
<simpara>Spring Cloud has an <literal>Environment</literal> pre-processor for decrypting
property values locally. It follows the same rules as the Config
Server, and has the same external configuration via <literal>encrypt.*</literal>. Thus
you can use encrypted values in the form <literal>{cipher}*</literal> and as long as
there is a valid key then they will be decrypted before the main
application context gets the <literal>Environment</literal>. To use the encryption
features in an application you need to include Spring Security RSA in
your classpath (Maven co-ordinates
"org.springframework.security:spring-security-rsa") and you also need
the full strength JCE extensions in your JVM.</simpara>
<simpara>If you are getting an exception due to "Illegal key size" and you are using Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. See the following links for more information:</simpara>
<simpara>Spring Cloud has an <literal>Environment</literal> pre-processor for decrypting property values locally.
It follows the same rules as the Config Server and has the same external configuration through <literal>encrypt.*</literal>.
Thus, you can use encrypted values in the form of <literal>{cipher}*</literal> and, as long as there is a valid key, they are decrypted before the main application context gets the <literal>Environment</literal> settings.
To use the encryption features in an application, you need to include Spring Security RSA in your classpath (Maven co-ordinates: "org.springframework.security:spring-security-rsa"), and you also need the full strength JCE extensions in your JVM.</simpara>
<simpara>If you get an exception due to "Illegal key size" and you use Sun’s JDK, you need to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files.
See the following links for more information:</simpara>
@ -307,46 +210,57 @@ the full strength JCE extensions in your JVM.</simpara>
@@ -307,46 +210,57 @@ the full strength JCE extensions in your JVM.</simpara>
<simpara>Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using).</simpara>
<simpara>Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.</simpara>
</section>
<sectionxml:id="_endpoints">
<title>Endpoints</title>
<simpara>For a Spring Boot Actuator application there are some additional management endpoints:</simpara>
<simpara>For a Spring Boot Actuator application, some additional management endpoints are available. You can use:</simpara>
<itemizedlist>
<listitem>
<simpara>POST to <literal>/env</literal> to update the <literal>Environment</literal> and rebind <literal>@ConfigurationProperties</literal> and log levels</simpara>
<simpara><literal>POST</literal> to <literal>/actuator/env</literal> to update the <literal>Environment</literal> and rebind <literal>@ConfigurationProperties</literal> and log levels.</simpara>
</listitem>
<listitem>
<simpara><literal>/refresh</literal> for re-loading the boot strap context and refreshing the <literal>@RefreshScope</literal> beans</simpara>
<simpara><literal>/actuator/refresh</literal> to re-load the boot strap context and refresh the <literal>@RefreshScope</literal> beans.</simpara>
</listitem>
<listitem>
<simpara><literal>/restart</literal> for closing the <literal>ApplicationContext</literal> and restarting it (disabled by default)</simpara>
<simpara><literal>/actuator/restart</literal> to close the <literal>ApplicationContext</literal> and restart it (disabled by default).</simpara>
</listitem>
<listitem>
<simpara><literal>/pause</literal> and <literal>/resume</literal> for calling the <literal>Lifecycle</literal> methods (<literal>stop()</literal> and <literal>start()</literal> on the <literal>ApplicationContext</literal>)</simpara>
<simpara><literal>/actuator/pause</literal> and <literal>/actuator/resume</literal> for calling the <literal>Lifecycle</literal> methods (<literal>stop()</literal> and <literal>start()</literal> on the <literal>ApplicationContext</literal>).</simpara>
<title>Spring Cloud Commons: Common Abstractions</title>
<simpara>Patterns such as service discovery, load balancing and circuit breakers lend themselves to a common abstraction layer that can be consumed by all Spring Cloud clients, independent of the implementation (e.g. discovery via Eureka or Consul).</simpara>
<simpara>Patterns such as service discovery, load balancing, and circuit breakers lend themselves to a common abstraction layer that can be consumed by all Spring Cloud clients, independent of the implementation (for example, discovery with Eureka or Consul).</simpara>
<sectionxml:id="__enablediscoveryclient">
<title>@EnableDiscoveryClient</title>
<simpara>Commons provides the <literal>@EnableDiscoveryClient</literal> annotation. This looks for implementations of the <literal>DiscoveryClient</literal> interface via <literal>META-INF/spring.factories</literal>. Implementations of Discovery Client will add a configuration class to <literal>spring.factories</literal> under the <literal>org.springframework.cloud.client.discovery.EnableDiscoveryClient</literal> key. Examples of <literal>DiscoveryClient</literal> implementations: are <linkxl:href="http://cloud.spring.io/spring-cloud-netflix/">Spring Cloud Netflix Eureka</link>, <linkxl:href="http://cloud.spring.io/spring-cloud-consul/">Spring Cloud Consul Discovery</link> and <linkxl:href="http://cloud.spring.io/spring-cloud-zookeeper/">Spring Cloud Zookeeper Discovery</link>.</simpara>
<simpara>By default, implementations of <literal>DiscoveryClient</literal> will auto-register the local Spring Boot server with the remote discovery server. This can be disabled by setting <literal>autoRegister=false</literal> in <literal>@EnableDiscoveryClient</literal>.</simpara>
<simpara>Spring Cloud Commons provides the <literal>@EnableDiscoveryClient</literal> annotation.
This looks for implementations of the <literal>DiscoveryClient</literal> interface with <literal>META-INF/spring.factories</literal>.
Implementations of the Discovery Client add a configuration class to <literal>spring.factories</literal> under the <literal>org.springframework.cloud.client.discovery.EnableDiscoveryClient</literal> key.
Examples of <literal>DiscoveryClient</literal> implementations include <linkxl:href="http://cloud.spring.io/spring-cloud-netflix/">Spring Cloud Netflix Eureka</link>, <linkxl:href="http://cloud.spring.io/spring-cloud-consul/">Spring Cloud Consul Discovery</link>, and <linkxl:href="http://cloud.spring.io/spring-cloud-zookeeper/">Spring Cloud Zookeeper Discovery</link>.</simpara>
<simpara>By default, implementations of <literal>DiscoveryClient</literal> auto-register the local Spring Boot server with the remote discovery server.
This behavior can be disabled by setting <literal>autoRegister=false</literal> in <literal>@EnableDiscoveryClient</literal>.</simpara>
<note>
<simpara>The use of <literal>@EnableDiscoveryClient</literal> is no longer required. It is enough to just have a <literal>DiscoveryClient</literal> implementation
on the classpath to cause the Spring Boot application to register with the service discovery server.</simpara>
<simpara><literal>@EnableDiscoveryClient</literal> is no longer required.
You can put a <literal>DiscoveryClient</literal> implementation on the classpath to cause the Spring Boot application to register with the service discovery server.</simpara>
</note>
<sectionxml:id="_health_indicator">
<title>Health Indicator</title>
<simpara>Commons creates a Spring Boot <literal>HealthIndicator</literal> that <literal>DiscoveryClient</literal> implementations can participate in by implementing <literal>DiscoveryHealthIndicator</literal>. To disable the composite <literal>HealthIndicator</literal> set <literal>spring.cloud.discovery.client.composite-indicator.enabled=false</literal>. A generic <literal>HealthIndicator</literal> based on <literal>DiscoveryClient</literal> is auto-configured (<literal>DiscoveryClientHealthIndicator</literal>). To disable it, set <literal>spring.cloud.discovery.client.health-indicator.enabled=false</literal>. To disable the description field of the <literal>DiscoveryClientHealthIndicator</literal> set <literal>spring.cloud.discovery.client.health-indicator.include-description=false</literal>, otherwise it can bubble up as the <literal>description</literal> of the rolled up <literal>HealthIndicator</literal>.</simpara>
<simpara>Commons creates a Spring Boot <literal>HealthIndicator</literal> that <literal>DiscoveryClient</literal> implementations can participate in by implementing <literal>DiscoveryHealthIndicator</literal>.
To disable the composite <literal>HealthIndicator</literal>, set <literal>spring.cloud.discovery.client.composite-indicator.enabled=false</literal>.
A generic <literal>HealthIndicator</literal> based on <literal>DiscoveryClient</literal> is auto-configured (<literal>DiscoveryClientHealthIndicator</literal>).
To disable it, set <literal>spring.cloud.discovery.client.health-indicator.enabled=false</literal>.
To disable the description field of the <literal>DiscoveryClientHealthIndicator</literal>, set <literal>spring.cloud.discovery.client.health-indicator.include-description=false</literal>.
Otherwise, it can bubble up as the <literal>description</literal> of the rolled up <literal>HealthIndicator</literal>.</simpara>
</section>
</section>
<sectionxml:id="_serviceregistry">
<title>ServiceRegistry</title>
<simpara>Commons now provides a <literal>ServiceRegistry</literal> interface which provides methods like <literal>register(Registration)</literal> and <literal>deregister(Registration)</literal> which allow you to provide custom registered services. <literal>Registration</literal> is a marker interface.</simpara>
<simpara>Commons now provides a <literal>ServiceRegistry</literal> interface that provides methods such as <literal>register(Registration)</literal> and <literal>deregister(Registration)</literal>, which let you provide custom registered services.
<literal>Registration</literal> is a marker interface.</simpara>
<simpara>The following example shows the <literal>ServiceRegistry</literal> in use:</simpara>
<simpara>By default, the <literal>ServiceRegistry</literal> implementation will auto-register the running service. To disable that behavior, there are two methods. You can set <literal>@EnableDiscoveryClient(autoRegister=false)</literal> to permanently disable auto-registration. You can also set <literal>spring.cloud.service-registry.auto-registration.enabled=false</literal> to disable the behavior via configuration.</simpara>
<simpara>By default, the <literal>ServiceRegistry</literal> implementation auto-registers the running service.
To disable that behavior, you can set:
* <literal>@EnableDiscoveryClient(autoRegister=false)</literal> to permanently disable auto-registration.
* <literal>spring.cloud.service-registry.auto-registration.enabled=false</literal> to disable the behavior through configuration.</simpara>
<simpara>A <literal>/service-registry</literal> actuator endpoint is provided by Commons. This endpoint relies on a <literal>Registration</literal> bean in the Spring Application Context. Calling <literal>/service-registry</literal> via a GET will return the status of the <literal>Registration</literal>. A POST to the same endpoint with a JSON body will change the status of the current <literal>Registration</literal> to the new value. The JSON body has to include the <literal>status</literal> field with the preferred value. Please see the documentation of the <literal>ServiceRegistry</literal> implementation you are using for the allowed values for updating the status and the values returned for the status. For instance, Eureka’s supported statuses are <literal>UP</literal>, <literal>DOWN</literal>, <literal>OUT_OF_SERVICE</literal> and <literal>UNKNOWN</literal>.</simpara>
<simpara>Spring Cloud Commons provides a <literal>/service-registry</literal> actuator endpoint.
This endpoint relies on a <literal>Registration</literal> bean in the Spring Application Context.
Calling <literal>/service-registry</literal> with GET returns the status of the <literal>Registration</literal>.
Using POST to the same endpoint with a JSON body changes the status of the current <literal>Registration</literal> to the new value.
The JSON body has to include the <literal>status</literal> field with the preferred value.
Please see the documentation of the <literal>ServiceRegistry</literal> implementation you use for the allowed values when updating the status and the values returned for the status.
For instance, Eureka’s supported statuses are <literal>UP</literal>, <literal>DOWN</literal>, <literal>OUT_OF_SERVICE</literal>, and <literal>UNKNOWN</literal>.</simpara>
<title>Spring RestTemplate as a Load Balancer Client</title>
<simpara><literal>RestTemplate</literal> can be automatically configured to use ribbon. To create a load balanced <literal>RestTemplate</literal> create a <literal>RestTemplate</literal><literal>@Bean</literal> and use the <literal>@LoadBalanced</literal> qualifier.</simpara>
<warning>
<simpara>A <literal>RestTemplate</literal> bean is no longer created via auto configuration. It must be created by individual applications.</simpara>
</warning>
<simpara><literal>RestTemplate</literal> can be automatically configured to use ribbon.
To create a load-balanced <literal>RestTemplate</literal>, create a <literal>RestTemplate</literal><literal>@Bean</literal> and use the <literal>@LoadBalanced</literal> qualifier, as shown in the following example:</simpara>
for details of how the <literal>RestTemplate</literal> is set up.</simpara>
<caution>
<simpara>A <literal>RestTemplate</literal> bean is no longer created through auto-configuration.
Individual applications must create it.</simpara>
</caution>
<simpara>The URI needs to use a virtual host name (that is, a service name, not a host name).
The Ribbon client is used to create a full physical address.
See <linkxl:href="https://github.com/spring-cloud/spring-cloud-netflix/blob/master/spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonAutoConfiguration.java">RibbonAutoConfiguration</link> for details of how the <literal>RestTemplate</literal> is set up.</simpara>
<title>Spring WebClient as a Load Balancer Client</title>
<simpara><literal>WebClient</literal> can be automatically configured to use the <literal>LoadBalancerClient</literal>. To create a load balanced <literal>WebClient</literal> create a <literal>WebClient.Builder</literal><literal>@Bean</literal> and use the <literal>@LoadBalanced</literal> qualifier.</simpara>
<simpara><literal>WebClient</literal> can be automatically configured to use the <literal>LoadBalancerClient</literal>.
To create a load-balanced <literal>WebClient</literal>, create a <literal>WebClient.Builder</literal><literal>@Bean</literal> and use the <literal>@LoadBalanced</literal> qualifier, as shown in the following example:</simpara>
@ -424,22 +349,18 @@ public class MyClass {
@@ -424,22 +349,18 @@ public class MyClass {
.retrieve().bodyToMono(String.class);
}
}</programlisting>
<simpara>The URI needs to use a virtual host name (ie. service name, not a host name).
<simpara>The URI needs to use a virtual host name (that is, a service name, not a host name).
The Ribbon client is used to create a full physical address.</simpara>
<sectionxml:id="_retrying_failed_requests">
<title>Retrying Failed Requests</title>
<simpara>A load balanced <literal>RestTemplate</literal> can be configured to retry failed requests.
By default this logic is disabled, you can enable it by adding <linkxl:href="https://github.com/spring-projects/spring-retry">Spring Retry</link> to your application’s classpath. The load balanced <literal>RestTemplate</literal> will
honor some of the Ribbon configuration values related to retrying failed requests. If
you would like to disable the retry logic with Spring Retry on the classpath
you can set <literal>spring.cloud.loadbalancer.retry.enabled=false</literal>.
The properties you can use are <literal>client.ribbon.MaxAutoRetries</literal>,
<literal>client.ribbon.MaxAutoRetriesNextServer</literal>, and <literal>client.ribbon.OkToRetryOnAllOperations</literal>.
See the <linkxl:href="https://github.com/Netflix/ribbon/wiki/Getting-Started#the-properties-file-sample-clientproperties">Ribbon documentation</link>
for a description of what there properties do.</simpara>
<simpara>If you would like to implement a <literal>BackOffPolicy</literal> in your retries you will need to
create a bean of type <literal>LoadBalancedBackOffPolicyFactory</literal>, and return the <literal>BackOffPolicy</literal>
you would like to use for a given service.</simpara>
<simpara>A load-balanced <literal>RestTemplate</literal> can be configured to retry failed requests.
By default, this logic is disabled.
You can enable it by adding <linkxl:href="https://github.com/spring-projects/spring-retry">Spring Retry</link> to your application’s classpath.
The load-balanced <literal>RestTemplate</literal> honors some of the Ribbon configuration values related to retrying failed requests.
You can use <literal>client.ribbon.MaxAutoRetries</literal>, <literal>client.ribbon.MaxAutoRetriesNextServer</literal>, and <literal>client.ribbon.OkToRetryOnAllOperations</literal> properties.
If you would like to disable the retry logic with Spring Retry on the classpath, you can set <literal>spring.cloud.loadbalancer.retry.enabled=false</literal>.
See the <linkxl:href="https://github.com/Netflix/ribbon/wiki/Getting-Started#the-properties-file-sample-clientproperties">Ribbon documentation</link> for a description of what these properties do.</simpara>
<simpara>If you would like to implement a <literal>BackOffPolicy</literal> in your retries, you need to create a bean of type <literal>LoadBalancedBackOffPolicyFactory</literal> and return the <literal>BackOffPolicy</literal> you would like to use for a given service, as shown in the following example:</simpara>
@ -491,12 +411,8 @@ public class MyConfiguration {
@@ -491,12 +411,8 @@ public class MyConfiguration {
</section>
<sectionxml:id="_multiple_resttemplate_objects">
<title>Multiple RestTemplate objects</title>
<simpara>If you want a <literal>RestTemplate</literal> that is not load balanced, create a <literal>RestTemplate</literal>
bean and inject it as normal. To access the load balanced <literal>RestTemplate</literal> use
the <literal>@LoadBalanced</literal> qualifier when you create your <literal>@Bean</literal>.</simpara>
<important>
<simpara>Notice the <literal>@Primary</literal> annotation on the plain <literal>RestTemplate</literal> declaration in the example below, to disambiguate the unqualified <literal>@Autowired</literal> injection.</simpara>
</important>
<simpara>If you want a <literal>RestTemplate</literal> that is not load-balanced, create a <literal>RestTemplate</literal> bean and inject it.
To access the load-balanced <literal>RestTemplate</literal>, use the <literal>@LoadBalanced</literal> qualifier when you create your <literal>@Bean</literal>, as shown in the following example:\</simpara>
<simpara>Notice the use of the <literal>@Primary</literal> annotation on the plain <literal>RestTemplate</literal> declaration in the preceding example to disambiguate the unqualified <literal>@Autowired</literal> injection.</simpara>
</important>
<tip>
<simpara>If you see errors like <literal>java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89</literal> try injecting <literal>RestOperations</literal> instead or setting <literal>spring.aop.proxyTargetClass=true</literal>.</simpara>
<simpara>If you see errors such as<literal>java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89</literal>, try injecting <literal>RestOperations</literal> or setting <literal>spring.aop.proxyTargetClass=true</literal>.</simpara>
</tip>
</section>
<sectionxml:id="loadbalanced-webclient">
<title>Spring WebFlux WebClient as a Load Balancer Client</title>
<simpara><literal>WebClient</literal> can be configured to use the <literal>LoadBalancerClient. A `LoadBalancerExchangeFilterFunction</literal> is auto-configured if spring-webflux is on the classpath.</simpara>
<simpara><literal>WebClient</literal> can be configured to use the <literal>LoadBalancerClient</literal>. <literal>LoadBalancerExchangeFilterFunction</literal> is auto-configured if <literal>spring-webflux</literal> is on the classpath. The following example shows how to configure a <literal>WebClient</literal> to use load balancer:</simpara>
<programlistinglanguage="java"linenumbering="unnumbered">public class MyClass {
@ -550,12 +469,14 @@ public class MyClass {
@@ -550,12 +469,14 @@ public class MyClass {
.bodyToMono(String.class);
}
}</programlisting>
<simpara>The URI needs to use a virtual host name (ie. service name, not a host name).
<simpara>The URI needs to use a virtual host name (that is, a service name, not a host name).
The <literal>LoadBalancerClient</literal> is used to create a full physical address.</simpara>
</section>
<sectionxml:id="ignore-network-interfaces">
<title>Ignore Network Interfaces</title>
<simpara>Sometimes it is useful to ignore certain named network interfaces so they can be excluded from Service Discovery registration (eg. running in a Docker container). A list of regular expressions can be set that will cause the desired network interfaces to be ignored. The following configuration will ignore the "docker0" interface and all interfaces that start with "veth".</simpara>
<simpara>Sometimes, it is useful to ignore certain named network interfaces so that they can be excluded from Service Discovery registration (for example, when running in a Docker container).
A list of regular expressions can be set to cause the desired network interfaces to be ignored.
The following configuration ignores the <literal>docker0</literal> interface and all interfaces that start with <literal>veth</literal>:</simpara>
<formalpara>
<title>application.yml</title>
<para>
@ -567,7 +488,7 @@ The <literal>LoadBalancerClient</literal> is used to create a full physical addr
@@ -567,7 +488,7 @@ The <literal>LoadBalancerClient</literal> is used to create a full physical addr
- veth.*</screen>
</para>
</formalpara>
<simpara>You can also force to use only specified network addresses using list of regular expressions:</simpara>
<simpara>You can also force the use of only specified network addresses by using a list of regular expressions, as shown in the following example:</simpara>
<formalpara>
<title>application.yml</title>
<para>
@ -579,43 +500,39 @@ The <literal>LoadBalancerClient</literal> is used to create a full physical addr
@@ -579,43 +500,39 @@ The <literal>LoadBalancerClient</literal> is used to create a full physical addr
- 10.0</screen>
</para>
</formalpara>
<simpara>You can also force to use only site local addresses. See <linkxl:href="https://docs.oracle.com/javase/8/docs/api/java/net/Inet4Address.html#isSiteLocalAddress--">Inet4Address.html.isSiteLocalAddress()</link> for more details what is site local address.</simpara>
<formalpara>
<title>application.yml</title>
<para>
<simpara>You can also force the use of only site-local addresses, as shown in the following example:
.application.yml</simpara>
<screen>spring:
cloud:
inetutils:
useOnlySiteLocalInterfaces: true</screen>
</para>
</formalpara>
<simpara>See <linkxl:href="https://docs.oracle.com/javase/8/docs/api/java/net/Inet4Address.html#isSiteLocalAddress--">Inet4Address.html.isSiteLocalAddress()</link> for more details about what constitutes a site-local address.</simpara>
</section>
<sectionxml:id="http-clients">
<title>HTTP Client Factories</title>
<simpara>Spring Cloud Commons provides beans for creating both Apache HTTP clients (<literal>ApacheHttpClientFactory</literal>)
as well as OK HTTP clients (<literal>OkHttpClientFactory</literal>). The <literal>OkHttpClientFactory</literal> bean will only be created
if the OK HTTP jar is on the classpath. In addition, Spring Cloud Commons provides beans for creating
the connection managers used by both clients, <literal>ApacheHttpClientConnectionManagerFactory</literal> for the Apache
HTTP client and <literal>OkHttpClientConnectionPoolFactory</literal> for the OK HTTP client. You can provide
your own implementation of these beans if you would like to customize how the HTTP clients are created
in downstream projects. In addition, if you provide a bean of type <literal>HttpClientBuilder</literal> and/or <literal>OkHttpClient.Builder</literal>,
the default factories will use these builders as the basis for the builders returned to downstream projects.
You can also disable the creation of these beans by setting
<literal>spring.cloud.httpclientfactories.apache.enabled</literal> or <literal>spring.cloud.httpclientfactories.ok.enabled</literal> to
<literal>false</literal>.</simpara>
<simpara>Spring Cloud Commons provides beans for creating both Apache HTTP clients (<literal>ApacheHttpClientFactory</literal>) and OK HTTP clients (<literal>OkHttpClientFactory</literal>).
The <literal>OkHttpClientFactory</literal> bean is created only if the OK HTTP jar is on the classpath.
In addition, Spring Cloud Commons provides beans for creating the connection managers used by both clients: <literal>ApacheHttpClientConnectionManagerFactory</literal> for the Apache HTTP client and <literal>OkHttpClientConnectionPoolFactory</literal> for the OK HTTP client.
If you would like to customize how the HTTP clients are created in downstream projects, you can provide your own implementation of these beans.
In addition, if you provide a bean of type <literal>HttpClientBuilder</literal> or <literal>OkHttpClient.Builder</literal>, the default factories use these builders as the basis for the builders returned to downstream projects.
You can also disable the creation of these beans by setting <literal>spring.cloud.httpclientfactories.apache.enabled</literal> or <literal>spring.cloud.httpclientfactories.ok.enabled</literal> to <literal>false</literal>.</simpara>
</section>
<sectionxml:id="enabled-features">
<title>Enabled Features</title>
<simpara>A <literal>/features</literal> actuator endpoint is provided by Commons. This endpoint returns features available on the classpath and if they are enabled or not. The information returned includes the feature type, name, version and vendor.</simpara>
<simpara>Spring Cloud Commons provides a <literal>/features</literal> actuator endpoint.
This endpoint returns features available on the classpath and whether they are enabled.
The information returned includes the feature type, name, version, and vendor.</simpara>
<sectionxml:id="_feature_types">
<title>Feature types</title>
<simpara>There are two types of 'features': abstract and named.</simpara>
<simpara>Abstract features are features where an interface or abstract class is defined that an implementation creates, such as <literal>DiscoveryClient</literal>, <literal>LoadBalancerClient</literal> or <literal>LockService</literal>. The abstract class or interface is used to find a bean of that type in the context. The version displayed is <literal>bean.getClass().getPackage().getImplementationVersion()</literal>.</simpara>
<simpara>Named features are features that don’t have a particular class they implement, such as "Circuit Breaker", "API Gateway", "Spring Cloud Bus", etc…​ These features require a name and a bean type.</simpara>
<simpara>Abstract features are features where an interface or abstract class is defined and that an implementation the creates, such as <literal>DiscoveryClient</literal>, <literal>LoadBalancerClient</literal>, or <literal>LockService</literal>.
The abstract class or interface is used to find a bean of that type in the context.
The version displayed is <literal>bean.getClass().getPackage().getImplementationVersion()</literal>.</simpara>
<simpara>Named features are features that do not have a particular class they implement, such as "Circuit Breaker", "API Gateway", "Spring Cloud Bus", and others. These features require a name and a bean type.</simpara>
</section>
<sectionxml:id="_declaring_features">
<title>Declaring features</title>
<simpara>Any module can declare any number of <literal>HasFeature</literal> beans. Some examples:</simpara>
<simpara>Any module can declare any number of <literal>HasFeature</literal> beans, as shown in the following examples:</simpara>