<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
</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>
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>