diff --git a/multi/multi__spring_cloud_commons_common_abstractions.html b/multi/multi__spring_cloud_commons_common_abstractions.html index 6efb18a1..f15fe674 100644 --- a/multi/multi__spring_cloud_commons_common_abstractions.html +++ b/multi/multi__spring_cloud_commons_common_abstractions.html @@ -1,7 +1,17 @@
-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).
Commons provides the @EnableDiscoveryClient annotation. This looks for implementations of the DiscoveryClient interface via META-INF/spring.factories. Implementations of Discovery Client will add a configuration class to spring.factories under the org.springframework.cloud.client.discovery.EnableDiscoveryClient key. Examples of DiscoveryClient implementations: are Spring Cloud Netflix Eureka, Spring Cloud Consul Discovery and Spring Cloud Zookeeper Discovery.
By default, implementations of DiscoveryClient will auto-register the local Spring Boot server with the remote discovery server. This can be disabled by setting autoRegister=false in @EnableDiscoveryClient.
![]() | Note |
|---|---|
The use of |
Commons creates a Spring Boot HealthIndicator that DiscoveryClient implementations can participate in by implementing DiscoveryHealthIndicator. To disable the composite HealthIndicator set spring.cloud.discovery.client.composite-indicator.enabled=false. A generic HealthIndicator based on DiscoveryClient is auto-configured (DiscoveryClientHealthIndicator). To disable it, set spring.cloud.discovery.client.health-indicator.enabled=false. To disable the description field of the DiscoveryClientHealthIndicator set spring.cloud.discovery.client.health-indicator.include-description=false, otherwise it can bubble up as the description of the rolled up HealthIndicator.
Commons now provides a ServiceRegistry interface which provides methods like register(Registration) and deregister(Registration) which allow you to provide custom registered services. Registration is a marker interface.
@Configuration +2. Spring Cloud Commons: Common Abstractions 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).
Spring Cloud Commons provides the
@EnableDiscoveryClientannotation. +This looks for implementations of theDiscoveryClientinterface withMETA-INF/spring.factories. +Implementations of the Discovery Client add a configuration class tospring.factoriesunder theorg.springframework.cloud.client.discovery.EnableDiscoveryClientkey. +Examples ofDiscoveryClientimplementations include Spring Cloud Netflix Eureka, Spring Cloud Consul Discovery, and Spring Cloud Zookeeper Discovery.By default, implementations of
DiscoveryClientauto-register the local Spring Boot server with the remote discovery server. +This behavior can be disabled by settingautoRegister=falsein@EnableDiscoveryClient.
Note
@EnableDiscoveryClientis no longer required. +You can put aDiscoveryClientimplementation on the classpath to cause the Spring Boot application to register with the service discovery server.Commons creates a Spring Boot
HealthIndicatorthatDiscoveryClientimplementations can participate in by implementingDiscoveryHealthIndicator. +To disable the compositeHealthIndicator, setspring.cloud.discovery.client.composite-indicator.enabled=false. +A genericHealthIndicatorbased onDiscoveryClientis auto-configured (DiscoveryClientHealthIndicator). +To disable it, setspring.cloud.discovery.client.health-indicator.enabled=false. +To disable the description field of theDiscoveryClientHealthIndicator, setspring.cloud.discovery.client.health-indicator.include-description=false. +Otherwise, it can bubble up as thedescriptionof the rolled upHealthIndicator.Commons now provides a
ServiceRegistryinterface that provides methods such asregister(Registration)andderegister(Registration), which let you provide custom registered services. +Registrationis a marker interface.The following example shows the
ServiceRegistryin use:@Configuration @EnableDiscoveryClient(autoRegister=false) public class MyConfiguration { private ServiceRegistry registry; @@ -10,12 +20,22 @@ on the classpath to cause the Spring Boot application to register with the servi this.registry = registry; } - // called via some external process, such as an event or a custom actuator endpoint + // called through some external process, such as an event or a custom actuator endpoint public void register() { Registration registration = constructRegistration(); this.registry.register(registration); } -}Each
ServiceRegistryimplementation has its ownRegistryimplementation.By default, the
ServiceRegistryimplementation will auto-register the running service. To disable that behavior, there are two methods. You can set@EnableDiscoveryClient(autoRegister=false)to permanently disable auto-registration. You can also setspring.cloud.service-registry.auto-registration.enabled=falseto disable the behavior via configuration.A
/service-registryactuator endpoint is provided by Commons. This endpoint relies on aRegistrationbean in the Spring Application Context. Calling/service-registryvia a GET will return the status of theRegistration. A POST to the same endpoint with a JSON body will change the status of the currentRegistrationto the new value. The JSON body has to include thestatusfield with the preferred value. Please see the documentation of theServiceRegistryimplementation you are using for the allowed values for updating the status and the values returned for the status. For instance, Eureka’s supported statuses areUP,DOWN,OUT_OF_SERVICEandUNKNOWN.
RestTemplatecan be automatically configured to use ribbon. To create a load balancedRestTemplatecreate aRestTemplate@Beanand use the@LoadBalancedqualifier.
Warning A
RestTemplatebean is no longer created via auto configuration. It must be created by individual applications.@Configuration +}Each
ServiceRegistryimplementation has its ownRegistryimplementation.By default, the
ServiceRegistryimplementation auto-registers the running service. +To disable that behavior, you can set: +*@EnableDiscoveryClient(autoRegister=false)to permanently disable auto-registration. +*spring.cloud.service-registry.auto-registration.enabled=falseto disable the behavior through configuration.Spring Cloud Commons provides a
/service-registryactuator endpoint. +This endpoint relies on aRegistrationbean in the Spring Application Context. +Calling/service-registrywith GET returns the status of theRegistration. +Using POST to the same endpoint with a JSON body changes the status of the currentRegistrationto the new value. +The JSON body has to include thestatusfield with the preferred value. +Please see the documentation of theServiceRegistryimplementation you use for the allowed values when updating the status and the values returned for the status. +For instance, Eureka’s supported statuses areUP,DOWN,OUT_OF_SERVICE, andUNKNOWN.
RestTemplatecan be automatically configured to use ribbon. +To create a load-balancedRestTemplate, create aRestTemplate@Beanand use the@LoadBalancedqualifier, as shown in the following example:@Configuration public class MyConfiguration { @LoadBalanced @@ -33,10 +53,11 @@ on the classpath to cause the Spring Boot application to register with the servi String results = restTemplate.getForObject("http://stores/stores", String.class); return results; } -}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. See -RibbonAutoConfiguration -for details of how the
RestTemplateis set up.
WebClientcan be automatically configured to use theLoadBalancerClient. To create a load balancedWebClientcreate aWebClient.Builder@Beanand use the@LoadBalancedqualifier.@Configuration +}
Caution A
RestTemplatebean is no longer created through auto-configuration. +Individual applications must create it.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 RibbonAutoConfiguration for details of how the
RestTemplateis set up.
WebClientcan be automatically configured to use theLoadBalancerClient. +To create a load-balancedWebClient, create aWebClient.Builder@Beanand use the@LoadBalancedqualifier, as shown in the following example:@Configuration public class MyConfiguration { @Bean @@ -54,18 +75,14 @@ for details of how theRestTemplateis set up.< return webClientBuilder.build().get().uri("http://stores/stores") .retrieve().bodyToMono(String.class); } -}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.
A load balanced
RestTemplatecan be configured to retry failed requests. -By default this logic is disabled, you can enable it by adding Spring Retry to your application’s classpath. The load balancedRestTemplatewill -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 setspring.cloud.loadbalancer.retry.enabled=false. -The properties you can use areclient.ribbon.MaxAutoRetries, -client.ribbon.MaxAutoRetriesNextServer, andclient.ribbon.OkToRetryOnAllOperations. -See the Ribbon documentation -for a description of what there properties do.If you would like to implement a
BackOffPolicyin your retries you will need to -create a bean of typeLoadBalancedBackOffPolicyFactory, and return theBackOffPolicy-you would like to use for a given service.@Configuration +}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.
A load-balanced
RestTemplatecan be configured to retry failed requests. +By default, this logic is disabled. +You can enable it by adding Spring Retry to your application’s classpath. +The load-balancedRestTemplatehonors some of the Ribbon configuration values related to retrying failed requests. +You can useclient.ribbon.MaxAutoRetries,client.ribbon.MaxAutoRetriesNextServer, andclient.ribbon.OkToRetryOnAllOperationsproperties. +If you would like to disable the retry logic with Spring Retry on the classpath, you can setspring.cloud.loadbalancer.retry.enabled=false. +See the Ribbon documentation for a description of what these properties do.If you would like to implement a
BackOffPolicyin your retries, you need to create a bean of typeLoadBalancedBackOffPolicyFactoryand return theBackOffPolicyyou would like to use for a given service, as shown in the following example:@Configuration public class MyConfiguration { @Bean LoadBalancedBackOffPolicyFactory backOffPolciyFactory() { @@ -76,10 +93,9 @@ you would like to use for a given service.
Note
clientin the above examples should be replaced with your Ribbon client’s -name.If you want to add one or more
RetryListenerto your retry you will need to +}
Note
clientin the preceding examples should be replaced with your Ribbon client’s name.If you want to add one or more
RetryListenerimplementations to your retry functionality, you need to create a bean of typeLoadBalancedRetryListenerFactoryand return theRetryListenerarray -you would like to use for a given service.@Configuration +you would like to use for a given service, as shown in the following example:@Configuration public class MyConfiguration { @Bean LoadBalancedRetryListenerFactory retryListenerFactory() { @@ -106,9 +122,8 @@ you would like to use for a given service.If you want a
RestTemplatethat is not load balanced, create aRestTemplate-bean and inject it as normal. To access the load balancedRestTemplateuse -the@LoadBalancedqualifier when you create your@Bean.
Important Notice the
@Primaryannotation on the plainRestTemplatedeclaration in the example below, to disambiguate the unqualified@Autowiredinjection.@Configuration +}If you want a
RestTemplatethat is not load-balanced, create aRestTemplatebean and inject it. +To access the load-balancedRestTemplate, use the@LoadBalancedqualifier when you create your@Bean, as shown in the following example:\@Configuration public class MyConfiguration { @LoadBalanced @@ -139,7 +154,7 @@ the@LoadBalancedqualifier when you create yourpublic String doStuff() { return restTemplate.getForObject("http://example.com", String.class); } -}
Tip If you see errors like
java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89try injectingRestOperationsinstead or settingspring.aop.proxyTargetClass=true.
WebClientcan be configured to use theLoadBalancerClient. A `LoadBalancerExchangeFilterFunctionis auto-configured if spring-webflux is on the classpath.public class MyClass { +}
Important Notice the use of the
@Primaryannotation on the plainRestTemplatedeclaration in the preceding example to disambiguate the unqualified@Autowiredinjection.
Tip If you see errors such as
java.lang.IllegalArgumentException: Can not set org.springframework.web.client.RestTemplate field com.my.app.Foo.restTemplate to com.sun.proxy.$Proxy89, try injectingRestOperationsor settingspring.aop.proxyTargetClass=true.
WebClientcan be configured to use theLoadBalancerClient.LoadBalancerExchangeFilterFunctionis auto-configured ifspring-webfluxis on the classpath. The following example shows how to configure aWebClientto use load balancer:public class MyClass { @Autowired private LoadBalancerExchangeFilterFunction lbFunction; @@ -152,37 +167,37 @@ the@LoadBalancedqualifier when you create yourclass); } -} The URI needs to use a virtual host name (ie. service name, not a host name). -The
LoadBalancerClientis used to create a full physical address.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".
application.yml. +}
The URI needs to use a virtual host name (that is, a service name, not a host name). +The
LoadBalancerClientis used to create a full physical address.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
docker0interface and all interfaces that start withveth:application.yml.
spring: cloud: inetutils: ignoredInterfaces: - docker0 - veth.*-
You can also force to use only specified network addresses using list of regular expressions:
application.yml. +
You can also force the use of only specified network addresses by using a list of regular expressions, as shown in the following example:
application.yml.
spring: cloud: inetutils: preferredNetworks: - 192.168 - 10.0-
You can also force to use only site local addresses. See Inet4Address.html.isSiteLocalAddress() for more details what is site local address.
application.yml. -
spring: +You can also force the use of only site-local addresses, as shown in the following example: +.application.yml
spring: cloud: inetutils: - useOnlySiteLocalInterfaces: true-
Spring Cloud Commons provides beans for creating both Apache HTTP clients (
ApacheHttpClientFactory) -as well as OK HTTP clients (OkHttpClientFactory). TheOkHttpClientFactorybean 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,ApacheHttpClientConnectionManagerFactoryfor the Apache -HTTP client andOkHttpClientConnectionPoolFactoryfor 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 typeHttpClientBuilderand/orOkHttpClient.Builder, -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 -spring.cloud.httpclientfactories.apache.enabledorspring.cloud.httpclientfactories.ok.enabledto -false.A
/featuresactuator 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.There are two types of 'features': abstract and named.
Abstract features are features where an interface or abstract class is defined that an implementation creates, such as
DiscoveryClient,LoadBalancerClientorLockService. The abstract class or interface is used to find a bean of that type in the context. The version displayed isbean.getClass().getPackage().getImplementationVersion().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.
Any module can declare any number of
HasFeaturebeans. Some examples:@Bean + useOnlySiteLocalInterfaces: trueSee Inet4Address.html.isSiteLocalAddress() for more details about what constitutes a site-local address.
Spring Cloud Commons provides beans for creating both Apache HTTP clients (
ApacheHttpClientFactory) and OK HTTP clients (OkHttpClientFactory). +TheOkHttpClientFactorybean 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:ApacheHttpClientConnectionManagerFactoryfor the Apache HTTP client andOkHttpClientConnectionPoolFactoryfor 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 typeHttpClientBuilderorOkHttpClient.Builder, 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 settingspring.cloud.httpclientfactories.apache.enabledorspring.cloud.httpclientfactories.ok.enabledtofalse.Spring Cloud Commons provides a
/featuresactuator 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.There are two types of 'features': abstract and named.
Abstract features are features where an interface or abstract class is defined and that an implementation the creates, such as
DiscoveryClient,LoadBalancerClient, orLockService. +The abstract class or interface is used to find a bean of that type in the context. +The version displayed isbean.getClass().getPackage().getImplementationVersion().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.
Any module can declare any number of
HasFeaturebeans, as shown in the following examples:@Bean public HasFeatures commonsFeatures() { return HasFeatures.abstractFeatures(DiscoveryClient.class, LoadBalancerClient.class); } diff --git a/multi/multi__spring_cloud_context_application_context_services.html b/multi/multi__spring_cloud_context_application_context_services.html index 7fde136f..aeafabf3 100644 --- a/multi/multi__spring_cloud_context_application_context_services.html +++ b/multi/multi__spring_cloud_context_application_context_services.html @@ -1,121 +1,51 @@ -1. Spring Cloud Context: Application Context Services \ No newline at end of file diff --git a/multi/multi_pr01.html b/multi/multi_pr01.html index 46cbd945..488b1557 100644 --- a/multi/multi_pr01.html +++ b/multi/multi_pr01.html @@ -1,3 +1,9 @@ -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.
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
Environment-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.The bootstrap context uses a different convention for locating -external configuration than the main application context, so instead -of
application.yml(or.properties) you usebootstrap.yml, -keeping the external configuration for bootstrap and main context -nicely separate. Example:bootstrap.yml. +
1. Spring Cloud Context: Application Context Services \ No newline at end of file +}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.
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
Environment, 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.The bootstrap context uses a different convention for locating external configuration than the main application context. +Instead of
application.yml(or.properties), you can usebootstrap.yml, keeping the external configuration for bootstrap and main context +nicely separate. +The following listing shows an example:bootstrap.yml.
spring: application: name: foo cloud: config: uri: ${SPRING_CONFIG_URI:http://localhost:8888}-
It is a good idea to set the
spring.application.name(in -bootstrap.ymlorapplication.yml) if your application needs any -application-specific configuration from the server.You can disable the bootstrap process completely by setting -
spring.cloud.bootstrap.enabled=false(e.g. in System properties).If you build an application context from
SpringApplicationor -SpringApplicationBuilder, 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:
- "bootstrap": an optional
CompositePropertySourceappears with high -priority if anyPropertySourceLocatorsare found in the Bootstrap -context, and they have non-empty properties. An example would be -properties from the Spring Cloud Config Server. See -below for instructions -on how to customize the contents of this property source.- "applicationConfig: [classpath:bootstrap.yml]" (and friends if -Spring profiles are active). If you have a
bootstrap.yml(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 theapplication.yml(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 below for -instructions on how to customize the contents of these property -sources.Because of the ordering rules of property sources the "bootstrap" -entries take precedence, but note that these do not contain any data -from
bootstrap.yml, which has very low precedence, but can be used -to set defaults.You can extend the context hierarchy by simply setting the parent -context of any
ApplicationContextyou create, e.g. using its own -interface, or with theSpringApplicationBuilderconvenience methods -(parent(),child()andsibling()). 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 differentspring.application.nameand -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).Note that the
SpringApplicationBuilderallows you to share an -Environmentamongst 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.The
bootstrap.yml(or.properties) location can be specified using -spring.cloud.bootstrap.name(default "bootstrap") or -spring.cloud.bootstrap.location(default empty), e.g. in System -properties. Those properties behave like thespring.config.*-variants with the same name, in fact they are used to set up the -bootstrapApplicationContextby setting those properties in its -Environment. If there is an active profile (from -spring.profiles.activeor through theEnvironmentAPI 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 -bootstrap-development.propertiesfor a "development" profile.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 -
spring.cloud.config.allowOverride=true(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: -spring.cloud.config.overrideNone=trueto override with any local -property source, and -spring.cloud.config.overrideSystemProperties=falseif only System -properties and env vars should override the remote settings, but not -the local config files.The bootstrap context can be trained to do anything you like by adding -entries to
/META-INF/spring.factoriesunder the key -org.springframework.cloud.bootstrap.BootstrapConfiguration. This is -a comma-separated list of Spring@Configurationclasses 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@Beansof type -ApplicationContextInitializer. Classes can be marked with an@Order-if you want to control the startup sequence (the default order is -"last").
Warning Be careful when adding custom
BootstrapConfigurationthat the -classes you add are not@ComponentScannedby 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@ComponentScanor@SpringBootApplication-annotated configuration classes.The bootstrap process ends by injecting initializers into the main -
SpringApplicationinstance (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 inspring.factoriesand then all@Beansof type -ApplicationContextInitializerare added to the main -SpringApplicationbefore it is started.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
PropertySourceLocatorto the -bootstrap context (viaspring.factories). You could use this to -insert additional properties from a different server, or from a -database, for instance.As an example, consider the following trivial custom locator:
@Configuration +If your application needs any application-specific configuration from the server, it is a good idea to set the
spring.application.name(inbootstrap.ymlorapplication.yml).You can disable the bootstrap process completely by setting
spring.cloud.bootstrap.enabled=false(for example, in system properties).If you build an application context from
SpringApplicationorSpringApplicationBuilder, 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:
- “bootstrap”: If any
PropertySourceLocatorsare found in the Bootstrap context and if they have non-empty properties, an optionalCompositePropertySourceappears with high priority. +An example would be properties from the Spring Cloud Config Server. +See “Section 1.6, “Customizing the Bootstrap Property Sources”” for instructions on how to customize the contents of this property source.- “applicationConfig: [classpath:bootstrap.yml]” (and related files if Spring profiles are active): If you have a
bootstrap.yml(or.properties), 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 theapplication.yml(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 “Section 1.3, “Changing the Location of Bootstrap Properties”” for instructions on how to customize the contents of these property sources.Because of the ordering rules of property sources, the “bootstrap” entries take precedence. +However, note that these do not contain any data from
bootstrap.yml, which has very low precedence but can be used to set defaults.You can extend the context hierarchy by setting the parent context of any
ApplicationContextyou create — for example, by using its own interface or with theSpringApplicationBuilderconvenience methods (parent(),child()andsibling()). +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 differentspring.application.nameand, 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).Note that the
SpringApplicationBuilderlets you share anEnvironmentamongst 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.The
bootstrap.yml(or.properties) location can be specified by settingspring.cloud.bootstrap.name(default:bootstrap) orspring.cloud.bootstrap.location(default: empty) — for example, in System properties. +Those properties behave like thespring.config.*variants with the same name. +In fact, they are used to set up the bootstrapApplicationContextby setting those properties in itsEnvironment. +If there is an active profile (fromspring.profiles.activeor through theEnvironmentAPI 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, frombootstrap-development.propertiesfor adevelopmentprofile.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
spring.cloud.config.allowOverride=true(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:
spring.cloud.config.overrideNone=true: Override from any local property source.spring.cloud.config.overrideSystemProperties=false: Only system properties and environment variables (but not the local config files) should override the remote settings.The bootstrap context can be set to do anything you like by adding entries to
/META-INF/spring.factoriesunder a key namedorg.springframework.cloud.bootstrap.BootstrapConfiguration. +This holds a comma-separated list of Spring@Configurationclasses 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@Beansof typeApplicationContextInitializer. +If you want to control the startup sequence, classes can be marked with an@Orderannotation (the default order islast).
Warning When adding custom
BootstrapConfiguration, be careful that the classes you add are not@ComponentScannedby 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@ComponentScanor@SpringBootApplicationannotated configuration classes.The bootstrap process ends by injecting initializers into the main
SpringApplicationinstance (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 inspring.factories. +Then, all@Beansof typeApplicationContextInitializerare added to the mainSpringApplicationbefore it is started.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
PropertySourceLocatorto the bootstrap context (throughspring.factories). +For instance, you can insert additional properties from a different server or from a database.As an example, consider the following custom locator:
@Configuration public class CustomPropertySourceLocator implements PropertySourceLocator { @Override @@ -124,67 +54,27 @@ database, for instance.As an example, consider the following trivial cust Collections.<String, Object>singletonMap("property.from.sample.custom.source", "worked as intended")); } -}
The
Environmentthat is passed in is the one for the -ApplicationContextabout 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 thisEnvironment(e.g. by -keying it on thespring.application.name, as is done in the default -Config Server property source locator).If you create a jar with this class in it and then add a -
META-INF/spring.factoriescontaining:org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocatorthen the "customProperty"
PropertySourcewill show up in any -application that includes that jar on its classpath.The application will listen for an
EnvironmentChangeEventand react -to the change in a couple of standard ways (additional -ApplicationListenerscan be added as@Beansby the user in the -normal way). When anEnvironmentChangeEventis observed it will -have a list of key values that have changed, and the application will -use those to:
- Re-bind any
@ConfigurationPropertiesbeans in the context- Set the logger levels for any properties in
logging.level.*Note that the Config Client does not by default poll for changes in -the
Environment, and generally we would not recommend that approach -for detecting changes (although you could set it up with a -@Scheduledannotation). If you have a scaled-out client application -then it is better to broadcast theEnvironmentChangeEventto all -the instances instead of having them polling for changes (e.g. using -the Spring Cloud -Bus).The
EnvironmentChangeEventcovers a large class of refresh use -cases, as long as you can actually make a change to theEnvironment-and publish the event (those APIs are public and part of core -Spring). You can verify the changes are bound to -@ConfigurationPropertiesbeans by visiting the/configprops-endpoint (normal Spring Boot Actuator feature). For instance a -DataSourcecan have itsmaxPoolSizechanged at runtime (the -defaultDataSourcecreated by Spring Boot is an -@ConfigurationPropertiesbean) and grow capacity -dynamically. Re-binding@ConfigurationPropertiesdoes 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 -ApplicationContext. To address those concerns we have -@RefreshScope.A Spring
@Beanthat is marked as@RefreshScopewill 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 aDataSourcehas open -connections when the database URL is changed via theEnvironment, 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.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.
The
RefreshScopeis a bean in the context and it has a public method -refreshAll()to refresh all beans in the scope by clearing the -target cache. This functionality is exposed in the -/refreshendpoint (over HTTP or JMX). There is also arefresh(String)method to refresh an -individual bean by name.
Note
@RefreshScopeworks (technically) on an@Configuration-class, but it might lead to surprising behaviour: e.g. it does not -mean that all the@Beansdefined in that class are themselves -@RefreshScope. Specifically, anything that depends on those beans -cannot rely on them being updated when a refresh is initiated, unless -it is itself in@RefreshScope(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@Configuration).Spring Cloud has an
Environmentpre-processor for decrypting -property values locally. It follows the same rules as the Config -Server, and has the same external configuration viaencrypt.*. Thus -you can use encrypted values in the form{cipher}*and as long as -there is a valid key then they will be decrypted before the main -application context gets theEnvironment. 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.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:
Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using).
For a Spring Boot Actuator application there are some additional management endpoints:
- POST to
/envto update theEnvironmentand rebind@ConfigurationPropertiesand log levels/refreshfor re-loading the boot strap context and refreshing the@RefreshScopebeans/restartfor closing theApplicationContextand restarting it (disabled by default)/pauseand/resumefor calling theLifecyclemethods (stop()andstart()on theApplicationContext)The
Environmentthat is passed in is the one for theApplicationContextabout 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 thisEnvironment(for example, by keying it onspring.application.name, as is done in the default Spring Cloud Config Server property source locator).If you create a jar with this class in it and then add a
META-INF/spring.factoriescontaining the following, thecustomPropertyPropertySourceappears in any application that includes that jar on its classpath:org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocatorThe application listens for an
EnvironmentChangeEventand reacts to the change in a couple of standard ways (additionalApplicationListenerscan be added as@Beansby the user in the normal way). +When anEnvironmentChangeEventis observed, it has a list of key values that have changed, and the application uses those to:
- Re-bind any
@ConfigurationPropertiesbeans in the context- Set the logger levels for any properties in
logging.level.*Note that the Config Client does not, by default, poll for changes in the
Environment. +Generally, we would not recommend that approach for detecting changes (although you could set it up with a +@Scheduledannotation). +If you have a scaled-out client application, it is better to broadcast theEnvironmentChangeEventto all the instances instead of having them polling for changes (for example, by using the Spring Cloud Bus).The
EnvironmentChangeEventcovers a large class of refresh use cases, as long as you can actually make a change to theEnvironmentand publish the event. +Note that those APIs are public and part of core Spring). +You can verify that the changes are bound to@ConfigurationPropertiesbeans by visiting the/configpropsendpoint (a normal Spring Boot Actuator feature). +For instance, aDataSourcecan have itsmaxPoolSizechanged at runtime (the defaultDataSourcecreated by Spring Boot is an@ConfigurationPropertiesbean) and grow capacity dynamically. +Re-binding@ConfigurationPropertiesdoes 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 wholeApplicationContext. +To address those concerns, we have@RefreshScope.When there is a configuration change, a Spring
@Beanthat is marked as@RefreshScopegets special treatment. +This feature addresses the problem of stateful beans that only get their configuration injected when they are initialized. +For instance, if aDataSourcehas open connections when the database URL is changed via theEnvironment, 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.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.
The
RefreshScopeis a bean in the context and has a publicrefreshAll()method to refresh all beans in the scope by clearing the target cache. +The/refreshendpoint exposes this functionality (over HTTP or JMX). +To refresh an individual bean by name, there is also arefresh(String)method.
Note
@RefreshScopeworks (technically) on an@Configurationclass, but it might lead to surprising behavior. +For example, it does not mean that all the@Beansdefined in that class are themselves in@RefreshScope. +Specifically, anything that depends on those beans cannot rely on them being updated when a refresh is initiated, unless it is itself in@RefreshScope. +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@Configuration).Spring Cloud has an
Environmentpre-processor for decrypting property values locally. +It follows the same rules as the Config Server and has the same external configuration throughencrypt.*. +Thus, you can use encrypted values in the form of{cipher}*and, as long as there is a valid key, they are decrypted before the main application context gets theEnvironmentsettings. +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.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:
Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.
For a Spring Boot Actuator application, some additional management endpoints are available. You can use:
POSTto/actuator/envto update theEnvironmentand rebind@ConfigurationPropertiesand log levels./actuator/refreshto re-load the boot strap context and refresh the@RefreshScopebeans./actuator/restartto close theApplicationContextand restart it (disabled by default)./actuator/pauseand/actuator/resumefor calling theLifecyclemethods (stop()andstart()on theApplicationContext).\ No newline at end of file +Cloud Native 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 12-factor Apps 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.
Many of those features are covered by Spring Boot, 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
ApplicationContextof 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).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:
Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using).
Note 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 github.
Cloud Native 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 12-factor Applications, 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.
Many of those features are covered by Spring Boot, 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
ApplicationContextof 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).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:
Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.
Note 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 github.