From 1f36d59772a1520e3b2c99ec7e401d6eb41e1a2e Mon Sep 17 00:00:00 2001 From: buildmaster Date: Wed, 28 Feb 2018 21:28:00 +0000 Subject: [PATCH] Sync docs from master to gh-pages --- ...ing_cloud_commons_common_abstractions.html | 103 ++-- ..._context_application_context_services.html | 238 +++------ multi/multi_pr01.html | 8 +- single/spring-cloud-commons.html | 345 +++++-------- spring-cloud-commons.xml | 477 ++++++++---------- 5 files changed, 455 insertions(+), 716 deletions(-) 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 @@ - 2. Spring Cloud Commons: Common Abstractions

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 (e.g. discovery via Eureka or Consul).

2.1 @EnableDiscoveryClient

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]Note

The use of @EnableDiscoveryClient is no longer required. It is enough to just have a DiscoveryClient implementation -on the classpath to cause the Spring Boot application to register with the service discovery server.

2.1.1 Health Indicator

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.

2.2 ServiceRegistry

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

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).

2.1 @EnableDiscoveryClient

Spring Cloud Commons provides the @EnableDiscoveryClient annotation. +This looks for implementations of the DiscoveryClient interface with META-INF/spring.factories. +Implementations of the Discovery Client add a configuration class to spring.factories under the org.springframework.cloud.client.discovery.EnableDiscoveryClient key. +Examples of DiscoveryClient implementations include Spring Cloud Netflix Eureka, Spring Cloud Consul Discovery, and Spring Cloud Zookeeper Discovery.

By default, implementations of DiscoveryClient auto-register the local Spring Boot server with the remote discovery server. +This behavior can be disabled by setting autoRegister=false in @EnableDiscoveryClient.

[Note]Note

@EnableDiscoveryClient is no longer required. +You can put a DiscoveryClient implementation on the classpath to cause the Spring Boot application to register with the service discovery server.

2.1.1 Health Indicator

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.

2.2 ServiceRegistry

Commons now provides a ServiceRegistry interface that provides methods such as register(Registration) and deregister(Registration), which let you provide custom registered services. +Registration is a marker interface.

The following example shows the ServiceRegistry in 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 ServiceRegistry implementation has its own Registry implementation.

2.2.1 ServiceRegistry Auto-Registration

By default, the ServiceRegistry implementation 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 set spring.cloud.service-registry.auto-registration.enabled=false to disable the behavior via configuration.

2.2.2 Service Registry Actuator Endpoint

A /service-registry actuator endpoint is provided by Commons. This endpoint relies on a Registration bean in the Spring Application Context. Calling /service-registry via a GET will return the status of the Registration. A POST to the same endpoint with a JSON body will change the status of the current Registration to the new value. The JSON body has to include the status field with the preferred value. Please see the documentation of the ServiceRegistry 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 UP, DOWN, OUT_OF_SERVICE and UNKNOWN.

2.3 Spring RestTemplate as a Load Balancer Client

RestTemplate can be automatically configured to use ribbon. To create a load balanced RestTemplate create a RestTemplate @Bean and use the @LoadBalanced qualifier.

[Warning]Warning

A RestTemplate bean is no longer created via auto configuration. It must be created by individual applications.

@Configuration
+}

Each ServiceRegistry implementation has its own Registry implementation.

2.2.1 ServiceRegistry Auto-Registration

By default, the ServiceRegistry implementation 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=false to disable the behavior through configuration.

2.2.2 Service Registry Actuator Endpoint

Spring Cloud Commons provides a /service-registry actuator endpoint. +This endpoint relies on a Registration bean in the Spring Application Context. +Calling /service-registry with GET returns the status of the Registration. +Using POST to the same endpoint with a JSON body changes the status of the current Registration to the new value. +The JSON body has to include the status field with the preferred value. +Please see the documentation of the ServiceRegistry 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 UP, DOWN, OUT_OF_SERVICE, and UNKNOWN.

2.3 Spring RestTemplate as a Load Balancer Client

RestTemplate can be automatically configured to use ribbon. +To create a load-balanced RestTemplate, create a RestTemplate @Bean and use the @LoadBalanced qualifier, 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 RestTemplate is set up.

2.4 Spring WebClient as a Load Balancer Client

WebClient can be automatically configured to use the LoadBalancerClient. To create a load balanced WebClient create a WebClient.Builder @Bean and use the @LoadBalanced qualifier.

@Configuration
+}
[Caution]Caution

A RestTemplate bean 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 RestTemplate is set up.

2.4 Spring WebClient as a Load Balancer Client

WebClient can be automatically configured to use the LoadBalancerClient. +To create a load-balanced WebClient, create a WebClient.Builder @Bean and use the @LoadBalanced qualifier, as shown in the following example:

@Configuration
 public class MyConfiguration {
 
 	@Bean
@@ -54,18 +75,14 @@ for details of how the RestTemplate is 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.

2.4.1 Retrying Failed Requests

A load balanced RestTemplate can 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 balanced RestTemplate 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 spring.cloud.loadbalancer.retry.enabled=false. -The properties you can use are client.ribbon.MaxAutoRetries, -client.ribbon.MaxAutoRetriesNextServer, and client.ribbon.OkToRetryOnAllOperations. -See the Ribbon documentation -for a description of what there properties do.

If you would like to implement a BackOffPolicy in your retries you will need to -create a bean of type LoadBalancedBackOffPolicyFactory, and return the BackOffPolicy -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.

2.4.1 Retrying Failed Requests

A load-balanced RestTemplate can 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-balanced RestTemplate honors some of the Ribbon configuration values related to retrying failed requests. +You can use client.ribbon.MaxAutoRetries, client.ribbon.MaxAutoRetriesNextServer, and client.ribbon.OkToRetryOnAllOperations properties. +If you would like to disable the retry logic with Spring Retry on the classpath, you can set spring.cloud.loadbalancer.retry.enabled=false. +See the Ribbon documentation for a description of what these properties do.

If you would like to implement a BackOffPolicy in your retries, you need to create a bean of type LoadBalancedBackOffPolicyFactory and return the BackOffPolicy you 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]Note

client in the above examples should be replaced with your Ribbon client’s -name.

If you want to add one or more RetryListener to your retry you will need to +}

[Note]Note

client in the preceding examples should be replaced with your Ribbon client’s name.

If you want to add one or more RetryListener implementations to your retry functionality, you need to create a bean of type LoadBalancedRetryListenerFactory and return the RetryListener array -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.

2.5 Multiple RestTemplate objects

If you want a RestTemplate that is not load balanced, create a RestTemplate -bean and inject it as normal. To access the load balanced RestTemplate use -the @LoadBalanced qualifier when you create your @Bean.

[Important]Important

Notice the @Primary annotation on the plain RestTemplate declaration in the example below, to disambiguate the unqualified @Autowired injection.

@Configuration
+}

2.5 Multiple RestTemplate objects

If you want a RestTemplate that is not load-balanced, create a RestTemplate bean and inject it. +To access the load-balanced RestTemplate, use the @LoadBalanced qualifier when you create your @Bean, as shown in the following example:\

@Configuration
 public class MyConfiguration {
 
     @LoadBalanced
@@ -139,7 +154,7 @@ the @LoadBalanced qualifier when you create your public String doStuff() {
         return restTemplate.getForObject("http://example.com", String.class);
     }
-}
[Tip]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.$Proxy89 try injecting RestOperations instead or setting spring.aop.proxyTargetClass=true.

2.6 Spring WebFlux WebClient as a Load Balancer Client

WebClient can be configured to use the LoadBalancerClient. A `LoadBalancerExchangeFilterFunction is auto-configured if spring-webflux is on the classpath.

public class MyClass {
+}
[Important]Important

Notice the use of the @Primary annotation on the plain RestTemplate declaration in the preceding example to disambiguate the unqualified @Autowired injection.

[Tip]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 injecting RestOperations or setting spring.aop.proxyTargetClass=true.

2.6 Spring WebFlux WebClient as a Load Balancer Client

WebClient can be configured to use the LoadBalancerClient. LoadBalancerExchangeFilterFunction is auto-configured if spring-webflux is on the classpath. The following example shows how to configure a WebClient to use load balancer:

public class MyClass {
     @Autowired
     private LoadBalancerExchangeFilterFunction lbFunction;
 
@@ -152,37 +167,37 @@ the @LoadBalanced qualifier when you create your class);
     }
-}

The URI needs to use a virtual host name (ie. service name, not a host name). -The LoadBalancerClient is used to create a full physical address.

2.7 Ignore Network Interfaces

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 LoadBalancerClient is used to create a full physical address.

2.7 Ignore Network Interfaces

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 docker0 interface and all interfaces that start with veth:

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

-

2.8 HTTP Client Factories

Spring Cloud Commons provides beans for creating both Apache HTTP clients (ApacheHttpClientFactory) -as well as OK HTTP clients (OkHttpClientFactory). The OkHttpClientFactory 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, ApacheHttpClientConnectionManagerFactory for the Apache -HTTP client and OkHttpClientConnectionPoolFactory 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 HttpClientBuilder and/or OkHttpClient.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.enabled or spring.cloud.httpclientfactories.ok.enabled to -false.

2.9 Enabled Features

A /features 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.

2.9.1 Feature types

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, LoadBalancerClient or LockService. The abstract class or interface is used to find a bean of that type in the context. The version displayed is bean.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.

2.9.2 Declaring features

Any module can declare any number of HasFeature beans. Some examples:

@Bean
+      useOnlySiteLocalInterfaces: true

See Inet4Address.html.isSiteLocalAddress() for more details about what constitutes a site-local address.

2.8 HTTP Client Factories

Spring Cloud Commons provides beans for creating both Apache HTTP clients (ApacheHttpClientFactory) and OK HTTP clients (OkHttpClientFactory). +The OkHttpClientFactory 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: ApacheHttpClientConnectionManagerFactory for the Apache HTTP client and OkHttpClientConnectionPoolFactory 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 HttpClientBuilder or OkHttpClient.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 setting spring.cloud.httpclientfactories.apache.enabled or spring.cloud.httpclientfactories.ok.enabled to false.

2.9 Enabled Features

Spring Cloud Commons provides a /features 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.

2.9.1 Feature types

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, or LockService. +The abstract class or interface is used to find a bean of that type in the context. +The version displayed is bean.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.

2.9.2 Declaring features

Any module can declare any number of HasFeature beans, 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

1. Spring Cloud Context: Application Context Services

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.

1.1 The Bootstrap Application Context

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 use bootstrap.yml, -keeping the external configuration for bootstrap and main context -nicely separate. Example:

bootstrap.yml.  + 1. Spring Cloud Context: Application Context Services

1. Spring Cloud Context: Application Context Services

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.

1.1 The Bootstrap Application Context

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 use bootstrap.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.yml or application.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).

1.2 Application Context Hierarchies

If you build an application context from SpringApplication or -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 CompositePropertySource appears with high -priority if any PropertySourceLocators are 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 the application.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 ApplicationContext you create, e.g. using its own -interface, or with the SpringApplicationBuilder convenience methods -(parent(), child() and sibling()). 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 spring.application.name 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).

Note that the SpringApplicationBuilder allows you to share an -Environment 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.

1.3 Changing the Location of Bootstrap Properties

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 the spring.config.* -variants with the same name, in fact they are used to set up the -bootstrap ApplicationContext by setting those properties in its -Environment. If there is an active profile (from -spring.profiles.active or through the Environment 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 -bootstrap-development.properties for a "development" profile.

1.4 Overriding the Values of Remote Properties

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=true to override with any local -property source, and -spring.cloud.config.overrideSystemProperties=false if only System -properties and env vars should override the remote settings, but not -the local config files.

1.5 Customizing the Bootstrap Configuration

The bootstrap context can be trained to do anything you like by adding -entries to /META-INF/spring.factories under the key -org.springframework.cloud.bootstrap.BootstrapConfiguration. This is -a comma-separated list of Spring @Configuration 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 @Beans of type -ApplicationContextInitializer. Classes can be marked with an @Order -if you want to control the startup sequence (the default order is -"last").

[Warning]Warning

Be careful when adding custom BootstrapConfiguration that the -classes you add are not @ComponentScanned 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 @ComponentScan or @SpringBootApplication -annotated configuration classes.

The bootstrap process ends by injecting initializers into the main -SpringApplication 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 spring.factories and then all @Beans of type -ApplicationContextInitializer are added to the main -SpringApplication before it is started.

1.6 Customizing the Bootstrap Property Sources

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 PropertySourceLocator to the -bootstrap context (via spring.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 (in bootstrap.yml or application.yml).

You can disable the bootstrap process completely by setting spring.cloud.bootstrap.enabled=false (for example, in system properties).

1.2 Application Context Hierarchies

If you build an application context from SpringApplication or 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 contains additional property sources, compared to building the same context without Spring Cloud Config. +The additional property sources are:

  • “bootstrap”: If any PropertySourceLocators are found in the Bootstrap context and if they have non-empty properties, an optional CompositePropertySource appears 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 the application.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 ApplicationContext you create — for example, by using its own interface or with the SpringApplicationBuilder convenience methods (parent(), child() and sibling()). +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 spring.application.name 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).

Note that the SpringApplicationBuilder lets you share an Environment 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.

1.3 Changing the Location of Bootstrap Properties

The bootstrap.yml (or .properties) location can be specified by setting spring.cloud.bootstrap.name (default: bootstrap) or spring.cloud.bootstrap.location (default: empty) — for example, in System properties. +Those properties behave like the spring.config.* variants with the same name. +In fact, they are used to set up the bootstrap ApplicationContext by setting those properties in its Environment. +If there is an active profile (from spring.profiles.active or through the Environment 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 bootstrap-development.properties for a development profile.

1.4 Overriding the Values of Remote Properties

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.

1.5 Customizing the Bootstrap Configuration

The bootstrap context can be set to do anything you like by adding entries to /META-INF/spring.factories under a key named org.springframework.cloud.bootstrap.BootstrapConfiguration. +This holds a comma-separated list of Spring @Configuration 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 @Beans of type ApplicationContextInitializer. +If you want to control the startup sequence, classes can be marked with an @Order annotation (the default order is last).

[Warning]Warning

When adding custom BootstrapConfiguration, be careful that the classes you add are not @ComponentScanned 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 @ComponentScan or @SpringBootApplication annotated configuration classes.

The bootstrap process ends by injecting initializers into the main SpringApplication 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 spring.factories. +Then, all @Beans of type ApplicationContextInitializer are added to the main SpringApplication before it is started.

1.6 Customizing the Bootstrap Property Sources

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 PropertySourceLocator to the bootstrap context (through spring.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 Environment that is passed in is the one for the -ApplicationContext 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 Environment (e.g. by -keying it on the spring.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.factories containing:

org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator

then the "customProperty" PropertySource will show up in any -application that includes that jar on its classpath.

1.7 Environment Changes

The application will listen for an EnvironmentChangeEvent and react -to the change in a couple of standard ways (additional -ApplicationListeners can be added as @Beans by the user in the -normal way). When an EnvironmentChangeEvent is observed it will -have a list of key values that have changed, and the application will -use those to:

  • Re-bind any @ConfigurationProperties beans 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 -@Scheduled annotation). If you have a scaled-out client application -then it is better to broadcast the EnvironmentChangeEvent to all -the instances instead of having them polling for changes (e.g. using -the Spring Cloud -Bus).

The EnvironmentChangeEvent covers a large class of refresh use -cases, as long as you can actually make a change to the Environment -and publish the event (those APIs are public and part of core -Spring). You can verify the changes are bound to -@ConfigurationProperties beans by visiting the /configprops -endpoint (normal Spring Boot Actuator feature). For instance a -DataSource can have its maxPoolSize changed at runtime (the -default DataSource created by Spring Boot is an -@ConfigurationProperties bean) and grow capacity -dynamically. Re-binding @ConfigurationProperties 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 -ApplicationContext. To address those concerns we have -@RefreshScope.

1.8 Refresh Scope

A Spring @Bean that is marked as @RefreshScope 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 DataSource has open -connections when the database URL is changed via the Environment, 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 RefreshScope is 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 -/refresh endpoint (over HTTP or JMX). There is also a refresh(String) method to refresh an -individual bean by name.

[Note]Note

@RefreshScope works (technically) on an @Configuration -class, but it might lead to surprising behaviour: e.g. it does not -mean that all the @Beans defined 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).

1.9 Encryption and Decryption

Spring Cloud has an Environment pre-processor for decrypting -property values locally. It follows the same rules as the Config -Server, and has the same external configuration via encrypt.*. 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 the Environment. 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).

1.10 Endpoints

For a Spring Boot Actuator application there are some additional management endpoints:

  • POST to /env to update the Environment and rebind @ConfigurationProperties and log levels
  • /refresh for re-loading the boot strap context and refreshing the @RefreshScope beans
  • /restart for closing the ApplicationContext and restarting it (disabled by default)
  • /pause and /resume for calling the Lifecycle methods (stop() and start() on the ApplicationContext)
\ No newline at end of file +}

The Environment that is passed in is the one for the ApplicationContext 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 Environment (for example, by keying it on spring.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.factories containing the following, the customProperty PropertySource appears in any application that includes that jar on its classpath:

org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator

1.7 Environment Changes

The application listens for an EnvironmentChangeEvent and reacts to the change in a couple of standard ways (additional ApplicationListeners can be added as @Beans by the user in the normal way). +When an EnvironmentChangeEvent is observed, it has a list of key values that have changed, and the application uses those to:

  • Re-bind any @ConfigurationProperties beans 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 +@Scheduled annotation). +If you have a scaled-out client application, it is better to broadcast the EnvironmentChangeEvent to all the instances instead of having them polling for changes (for example, by using the Spring Cloud Bus).

The EnvironmentChangeEvent covers a large class of refresh use cases, as long as you can actually make a change to the Environment and publish the event. +Note that those APIs are public and part of core Spring). +You can verify that the changes are bound to @ConfigurationProperties beans by visiting the /configprops endpoint (a normal Spring Boot Actuator feature). +For instance, a DataSource can have its maxPoolSize changed at runtime (the default DataSource created by Spring Boot is an @ConfigurationProperties bean) and grow capacity dynamically. +Re-binding @ConfigurationProperties 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 ApplicationContext. +To address those concerns, we have @RefreshScope.

1.8 Refresh Scope

When there is a configuration change, a Spring @Bean that is marked as @RefreshScope 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 DataSource has open connections when the database URL is changed via the Environment, 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 RefreshScope is a bean in the context and has a public refreshAll() method to refresh all beans in the scope by clearing the target cache. +The /refresh endpoint exposes this functionality (over HTTP or JMX). +To refresh an individual bean by name, there is also a refresh(String) method.

[Note]Note

@RefreshScope works (technically) on an @Configuration class, but it might lead to surprising behavior. +For example, it does not mean that all the @Beans defined 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).

1.9 Encryption and Decryption

Spring Cloud has an Environment pre-processor for decrypting property values locally. +It follows the same rules as the Config Server and has the same external configuration through encrypt.*. +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 the Environment 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.

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.

1.10 Endpoints

For a Spring Boot Actuator application, some additional management endpoints are available. You can use:

  • POST to /actuator/env to update the Environment and rebind @ConfigurationProperties and log levels.
  • /actuator/refresh to re-load the boot strap context and refresh the @RefreshScope beans.
  • /actuator/restart to close the ApplicationContext and restart it (disabled by default).
  • /actuator/pause and /actuator/resume for calling the Lifecycle methods (stop() and start() on the ApplicationContext).
\ 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 @@ -

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 ApplicationContext 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).

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]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.

\ 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 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 ApplicationContext 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).

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]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.

\ No newline at end of file diff --git a/single/spring-cloud-commons.html b/single/spring-cloud-commons.html index 92725f49..70da86a1 100644 --- a/single/spring-cloud-commons.html +++ b/single/spring-cloud-commons.html @@ -1,121 +1,57 @@ - Cloud Native Applications

Cloud Native Applications


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 ApplicationContext 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).

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]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.

1. Spring Cloud Context: Application Context Services

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.

1.1 The Bootstrap Application Context

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 use bootstrap.yml, -keeping the external configuration for bootstrap and main context -nicely separate. Example:

bootstrap.yml.  + Cloud Native Applications

Cloud Native Applications


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 ApplicationContext 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).

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]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.

1. Spring Cloud Context: Application Context Services

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.

1.1 The Bootstrap Application Context

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 use bootstrap.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.yml or application.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).

1.2 Application Context Hierarchies

If you build an application context from SpringApplication or -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 CompositePropertySource appears with high -priority if any PropertySourceLocators are 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 the application.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 ApplicationContext you create, e.g. using its own -interface, or with the SpringApplicationBuilder convenience methods -(parent(), child() and sibling()). 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 spring.application.name 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).

Note that the SpringApplicationBuilder allows you to share an -Environment 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.

1.3 Changing the Location of Bootstrap Properties

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 the spring.config.* -variants with the same name, in fact they are used to set up the -bootstrap ApplicationContext by setting those properties in its -Environment. If there is an active profile (from -spring.profiles.active or through the Environment 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 -bootstrap-development.properties for a "development" profile.

1.4 Overriding the Values of Remote Properties

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=true to override with any local -property source, and -spring.cloud.config.overrideSystemProperties=false if only System -properties and env vars should override the remote settings, but not -the local config files.

1.5 Customizing the Bootstrap Configuration

The bootstrap context can be trained to do anything you like by adding -entries to /META-INF/spring.factories under the key -org.springframework.cloud.bootstrap.BootstrapConfiguration. This is -a comma-separated list of Spring @Configuration 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 @Beans of type -ApplicationContextInitializer. Classes can be marked with an @Order -if you want to control the startup sequence (the default order is -"last").

[Warning]Warning

Be careful when adding custom BootstrapConfiguration that the -classes you add are not @ComponentScanned 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 @ComponentScan or @SpringBootApplication -annotated configuration classes.

The bootstrap process ends by injecting initializers into the main -SpringApplication 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 spring.factories and then all @Beans of type -ApplicationContextInitializer are added to the main -SpringApplication before it is started.

1.6 Customizing the Bootstrap Property Sources

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 PropertySourceLocator to the -bootstrap context (via spring.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 (in bootstrap.yml or application.yml).

You can disable the bootstrap process completely by setting spring.cloud.bootstrap.enabled=false (for example, in system properties).

1.2 Application Context Hierarchies

If you build an application context from SpringApplication or 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 contains additional property sources, compared to building the same context without Spring Cloud Config. +The additional property sources are:

  • “bootstrap”: If any PropertySourceLocators are found in the Bootstrap context and if they have non-empty properties, an optional CompositePropertySource appears 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 the application.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 ApplicationContext you create — for example, by using its own interface or with the SpringApplicationBuilder convenience methods (parent(), child() and sibling()). +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 spring.application.name 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).

Note that the SpringApplicationBuilder lets you share an Environment 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.

1.3 Changing the Location of Bootstrap Properties

The bootstrap.yml (or .properties) location can be specified by setting spring.cloud.bootstrap.name (default: bootstrap) or spring.cloud.bootstrap.location (default: empty) — for example, in System properties. +Those properties behave like the spring.config.* variants with the same name. +In fact, they are used to set up the bootstrap ApplicationContext by setting those properties in its Environment. +If there is an active profile (from spring.profiles.active or through the Environment 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 bootstrap-development.properties for a development profile.

1.4 Overriding the Values of Remote Properties

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.

1.5 Customizing the Bootstrap Configuration

The bootstrap context can be set to do anything you like by adding entries to /META-INF/spring.factories under a key named org.springframework.cloud.bootstrap.BootstrapConfiguration. +This holds a comma-separated list of Spring @Configuration 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 @Beans of type ApplicationContextInitializer. +If you want to control the startup sequence, classes can be marked with an @Order annotation (the default order is last).

[Warning]Warning

When adding custom BootstrapConfiguration, be careful that the classes you add are not @ComponentScanned 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 @ComponentScan or @SpringBootApplication annotated configuration classes.

The bootstrap process ends by injecting initializers into the main SpringApplication 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 spring.factories. +Then, all @Beans of type ApplicationContextInitializer are added to the main SpringApplication before it is started.

1.6 Customizing the Bootstrap Property Sources

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 PropertySourceLocator to the bootstrap context (through spring.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,71 +60,41 @@ database, for instance.

As an example, consider the following trivial cust Collections.<String, Object>singletonMap("property.from.sample.custom.source", "worked as intended")); } -}

The Environment that is passed in is the one for the -ApplicationContext 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 Environment (e.g. by -keying it on the spring.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.factories containing:

org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator

then the "customProperty" PropertySource will show up in any -application that includes that jar on its classpath.

1.7 Environment Changes

The application will listen for an EnvironmentChangeEvent and react -to the change in a couple of standard ways (additional -ApplicationListeners can be added as @Beans by the user in the -normal way). When an EnvironmentChangeEvent is observed it will -have a list of key values that have changed, and the application will -use those to:

  • Re-bind any @ConfigurationProperties beans 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 -@Scheduled annotation). If you have a scaled-out client application -then it is better to broadcast the EnvironmentChangeEvent to all -the instances instead of having them polling for changes (e.g. using -the Spring Cloud -Bus).

The EnvironmentChangeEvent covers a large class of refresh use -cases, as long as you can actually make a change to the Environment -and publish the event (those APIs are public and part of core -Spring). You can verify the changes are bound to -@ConfigurationProperties beans by visiting the /configprops -endpoint (normal Spring Boot Actuator feature). For instance a -DataSource can have its maxPoolSize changed at runtime (the -default DataSource created by Spring Boot is an -@ConfigurationProperties bean) and grow capacity -dynamically. Re-binding @ConfigurationProperties 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 -ApplicationContext. To address those concerns we have -@RefreshScope.

1.8 Refresh Scope

A Spring @Bean that is marked as @RefreshScope 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 DataSource has open -connections when the database URL is changed via the Environment, 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 RefreshScope is 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 -/refresh endpoint (over HTTP or JMX). There is also a refresh(String) method to refresh an -individual bean by name.

[Note]Note

@RefreshScope works (technically) on an @Configuration -class, but it might lead to surprising behaviour: e.g. it does not -mean that all the @Beans defined 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).

1.9 Encryption and Decryption

Spring Cloud has an Environment pre-processor for decrypting -property values locally. It follows the same rules as the Config -Server, and has the same external configuration via encrypt.*. 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 the Environment. 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).

1.10 Endpoints

For a Spring Boot Actuator application there are some additional management endpoints:

  • POST to /env to update the Environment and rebind @ConfigurationProperties and log levels
  • /refresh for re-loading the boot strap context and refreshing the @RefreshScope beans
  • /restart for closing the ApplicationContext and restarting it (disabled by default)
  • /pause and /resume for calling the Lifecycle methods (stop() and start() on the ApplicationContext)

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 (e.g. discovery via Eureka or Consul).

2.1 @EnableDiscoveryClient

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]Note

The use of @EnableDiscoveryClient is no longer required. It is enough to just have a DiscoveryClient implementation -on the classpath to cause the Spring Boot application to register with the service discovery server.

2.1.1 Health Indicator

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.

2.2 ServiceRegistry

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
+}

The Environment that is passed in is the one for the ApplicationContext 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 Environment (for example, by keying it on spring.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.factories containing the following, the customProperty PropertySource appears in any application that includes that jar on its classpath:

org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator

1.7 Environment Changes

The application listens for an EnvironmentChangeEvent and reacts to the change in a couple of standard ways (additional ApplicationListeners can be added as @Beans by the user in the normal way). +When an EnvironmentChangeEvent is observed, it has a list of key values that have changed, and the application uses those to:

  • Re-bind any @ConfigurationProperties beans 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 +@Scheduled annotation). +If you have a scaled-out client application, it is better to broadcast the EnvironmentChangeEvent to all the instances instead of having them polling for changes (for example, by using the Spring Cloud Bus).

The EnvironmentChangeEvent covers a large class of refresh use cases, as long as you can actually make a change to the Environment and publish the event. +Note that those APIs are public and part of core Spring). +You can verify that the changes are bound to @ConfigurationProperties beans by visiting the /configprops endpoint (a normal Spring Boot Actuator feature). +For instance, a DataSource can have its maxPoolSize changed at runtime (the default DataSource created by Spring Boot is an @ConfigurationProperties bean) and grow capacity dynamically. +Re-binding @ConfigurationProperties 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 ApplicationContext. +To address those concerns, we have @RefreshScope.

1.8 Refresh Scope

When there is a configuration change, a Spring @Bean that is marked as @RefreshScope 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 DataSource has open connections when the database URL is changed via the Environment, 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 RefreshScope is a bean in the context and has a public refreshAll() method to refresh all beans in the scope by clearing the target cache. +The /refresh endpoint exposes this functionality (over HTTP or JMX). +To refresh an individual bean by name, there is also a refresh(String) method.

[Note]Note

@RefreshScope works (technically) on an @Configuration class, but it might lead to surprising behavior. +For example, it does not mean that all the @Beans defined 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).

1.9 Encryption and Decryption

Spring Cloud has an Environment pre-processor for decrypting property values locally. +It follows the same rules as the Config Server and has the same external configuration through encrypt.*. +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 the Environment 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.

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.

1.10 Endpoints

For a Spring Boot Actuator application, some additional management endpoints are available. You can use:

  • POST to /actuator/env to update the Environment and rebind @ConfigurationProperties and log levels.
  • /actuator/refresh to re-load the boot strap context and refresh the @RefreshScope beans.
  • /actuator/restart to close the ApplicationContext and restart it (disabled by default).
  • /actuator/pause and /actuator/resume for calling the Lifecycle methods (stop() and start() on the ApplicationContext).

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).

2.1 @EnableDiscoveryClient

Spring Cloud Commons provides the @EnableDiscoveryClient annotation. +This looks for implementations of the DiscoveryClient interface with META-INF/spring.factories. +Implementations of the Discovery Client add a configuration class to spring.factories under the org.springframework.cloud.client.discovery.EnableDiscoveryClient key. +Examples of DiscoveryClient implementations include Spring Cloud Netflix Eureka, Spring Cloud Consul Discovery, and Spring Cloud Zookeeper Discovery.

By default, implementations of DiscoveryClient auto-register the local Spring Boot server with the remote discovery server. +This behavior can be disabled by setting autoRegister=false in @EnableDiscoveryClient.

[Note]Note

@EnableDiscoveryClient is no longer required. +You can put a DiscoveryClient implementation on the classpath to cause the Spring Boot application to register with the service discovery server.

2.1.1 Health Indicator

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.

2.2 ServiceRegistry

Commons now provides a ServiceRegistry interface that provides methods such as register(Registration) and deregister(Registration), which let you provide custom registered services. +Registration is a marker interface.

The following example shows the ServiceRegistry in use:

@Configuration
 @EnableDiscoveryClient(autoRegister=false)
 public class MyConfiguration {
     private ServiceRegistry registry;
@@ -197,12 +103,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 ServiceRegistry implementation has its own Registry implementation.

2.2.1 ServiceRegistry Auto-Registration

By default, the ServiceRegistry implementation 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 set spring.cloud.service-registry.auto-registration.enabled=false to disable the behavior via configuration.

2.2.2 Service Registry Actuator Endpoint

A /service-registry actuator endpoint is provided by Commons. This endpoint relies on a Registration bean in the Spring Application Context. Calling /service-registry via a GET will return the status of the Registration. A POST to the same endpoint with a JSON body will change the status of the current Registration to the new value. The JSON body has to include the status field with the preferred value. Please see the documentation of the ServiceRegistry 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 UP, DOWN, OUT_OF_SERVICE and UNKNOWN.

2.3 Spring RestTemplate as a Load Balancer Client

RestTemplate can be automatically configured to use ribbon. To create a load balanced RestTemplate create a RestTemplate @Bean and use the @LoadBalanced qualifier.

[Warning]Warning

A RestTemplate bean is no longer created via auto configuration. It must be created by individual applications.

@Configuration
+}

Each ServiceRegistry implementation has its own Registry implementation.

2.2.1 ServiceRegistry Auto-Registration

By default, the ServiceRegistry implementation 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=false to disable the behavior through configuration.

2.2.2 Service Registry Actuator Endpoint

Spring Cloud Commons provides a /service-registry actuator endpoint. +This endpoint relies on a Registration bean in the Spring Application Context. +Calling /service-registry with GET returns the status of the Registration. +Using POST to the same endpoint with a JSON body changes the status of the current Registration to the new value. +The JSON body has to include the status field with the preferred value. +Please see the documentation of the ServiceRegistry 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 UP, DOWN, OUT_OF_SERVICE, and UNKNOWN.

2.3 Spring RestTemplate as a Load Balancer Client

RestTemplate can be automatically configured to use ribbon. +To create a load-balanced RestTemplate, create a RestTemplate @Bean and use the @LoadBalanced qualifier, as shown in the following example:

@Configuration
 public class MyConfiguration {
 
     @LoadBalanced
@@ -220,10 +136,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 RestTemplate is set up.

2.4 Spring WebClient as a Load Balancer Client

WebClient can be automatically configured to use the LoadBalancerClient. To create a load balanced WebClient create a WebClient.Builder @Bean and use the @LoadBalanced qualifier.

@Configuration
+}
[Caution]Caution

A RestTemplate bean 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 RestTemplate is set up.

2.4 Spring WebClient as a Load Balancer Client

WebClient can be automatically configured to use the LoadBalancerClient. +To create a load-balanced WebClient, create a WebClient.Builder @Bean and use the @LoadBalanced qualifier, as shown in the following example:

@Configuration
 public class MyConfiguration {
 
 	@Bean
@@ -241,18 +158,14 @@ for details of how the RestTemplate is 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.

2.4.1 Retrying Failed Requests

A load balanced RestTemplate can 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 balanced RestTemplate 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 spring.cloud.loadbalancer.retry.enabled=false. -The properties you can use are client.ribbon.MaxAutoRetries, -client.ribbon.MaxAutoRetriesNextServer, and client.ribbon.OkToRetryOnAllOperations. -See the Ribbon documentation -for a description of what there properties do.

If you would like to implement a BackOffPolicy in your retries you will need to -create a bean of type LoadBalancedBackOffPolicyFactory, and return the BackOffPolicy -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.

2.4.1 Retrying Failed Requests

A load-balanced RestTemplate can 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-balanced RestTemplate honors some of the Ribbon configuration values related to retrying failed requests. +You can use client.ribbon.MaxAutoRetries, client.ribbon.MaxAutoRetriesNextServer, and client.ribbon.OkToRetryOnAllOperations properties. +If you would like to disable the retry logic with Spring Retry on the classpath, you can set spring.cloud.loadbalancer.retry.enabled=false. +See the Ribbon documentation for a description of what these properties do.

If you would like to implement a BackOffPolicy in your retries, you need to create a bean of type LoadBalancedBackOffPolicyFactory and return the BackOffPolicy you would like to use for a given service, as shown in the following example:

@Configuration
 public class MyConfiguration {
     @Bean
     LoadBalancedBackOffPolicyFactory backOffPolciyFactory() {
@@ -263,10 +176,9 @@ you would like to use for a given service.

[Note]Note

client in the above examples should be replaced with your Ribbon client’s -name.

If you want to add one or more RetryListener to your retry you will need to +}

[Note]Note

client in the preceding examples should be replaced with your Ribbon client’s name.

If you want to add one or more RetryListener implementations to your retry functionality, you need to create a bean of type LoadBalancedRetryListenerFactory and return the RetryListener array -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() {
@@ -293,9 +205,8 @@ you would like to use for a given service.

2.5 Multiple RestTemplate objects

If you want a RestTemplate that is not load balanced, create a RestTemplate -bean and inject it as normal. To access the load balanced RestTemplate use -the @LoadBalanced qualifier when you create your @Bean.

[Important]Important

Notice the @Primary annotation on the plain RestTemplate declaration in the example below, to disambiguate the unqualified @Autowired injection.

@Configuration
+}

2.5 Multiple RestTemplate objects

If you want a RestTemplate that is not load-balanced, create a RestTemplate bean and inject it. +To access the load-balanced RestTemplate, use the @LoadBalanced qualifier when you create your @Bean, as shown in the following example:\

@Configuration
 public class MyConfiguration {
 
     @LoadBalanced
@@ -326,7 +237,7 @@ the @LoadBalanced qualifier when you create your public String doStuff() {
         return restTemplate.getForObject("http://example.com", String.class);
     }
-}
[Tip]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.$Proxy89 try injecting RestOperations instead or setting spring.aop.proxyTargetClass=true.

2.6 Spring WebFlux WebClient as a Load Balancer Client

WebClient can be configured to use the LoadBalancerClient. A `LoadBalancerExchangeFilterFunction is auto-configured if spring-webflux is on the classpath.

public class MyClass {
+}
[Important]Important

Notice the use of the @Primary annotation on the plain RestTemplate declaration in the preceding example to disambiguate the unqualified @Autowired injection.

[Tip]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 injecting RestOperations or setting spring.aop.proxyTargetClass=true.

2.6 Spring WebFlux WebClient as a Load Balancer Client

WebClient can be configured to use the LoadBalancerClient. LoadBalancerExchangeFilterFunction is auto-configured if spring-webflux is on the classpath. The following example shows how to configure a WebClient to use load balancer:

public class MyClass {
     @Autowired
     private LoadBalancerExchangeFilterFunction lbFunction;
 
@@ -339,37 +250,37 @@ the @LoadBalanced qualifier when you create your class);
     }
-}

The URI needs to use a virtual host name (ie. service name, not a host name). -The LoadBalancerClient is used to create a full physical address.

2.7 Ignore Network Interfaces

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 LoadBalancerClient is used to create a full physical address.

2.7 Ignore Network Interfaces

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 docker0 interface and all interfaces that start with veth:

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

-

2.8 HTTP Client Factories

Spring Cloud Commons provides beans for creating both Apache HTTP clients (ApacheHttpClientFactory) -as well as OK HTTP clients (OkHttpClientFactory). The OkHttpClientFactory 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, ApacheHttpClientConnectionManagerFactory for the Apache -HTTP client and OkHttpClientConnectionPoolFactory 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 HttpClientBuilder and/or OkHttpClient.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.enabled or spring.cloud.httpclientfactories.ok.enabled to -false.

2.9 Enabled Features

A /features 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.

2.9.1 Feature types

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, LoadBalancerClient or LockService. The abstract class or interface is used to find a bean of that type in the context. The version displayed is bean.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.

2.9.2 Declaring features

Any module can declare any number of HasFeature beans. Some examples:

@Bean
+      useOnlySiteLocalInterfaces: true

See Inet4Address.html.isSiteLocalAddress() for more details about what constitutes a site-local address.

2.8 HTTP Client Factories

Spring Cloud Commons provides beans for creating both Apache HTTP clients (ApacheHttpClientFactory) and OK HTTP clients (OkHttpClientFactory). +The OkHttpClientFactory 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: ApacheHttpClientConnectionManagerFactory for the Apache HTTP client and OkHttpClientConnectionPoolFactory 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 HttpClientBuilder or OkHttpClient.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 setting spring.cloud.httpclientfactories.apache.enabled or spring.cloud.httpclientfactories.ok.enabled to false.

2.9 Enabled Features

Spring Cloud Commons provides a /features 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.

2.9.1 Feature types

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, or LockService. +The abstract class or interface is used to find a bean of that type in the context. +The version displayed is bean.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.

2.9.2 Declaring features

Any module can declare any number of HasFeature beans, as shown in the following examples:

@Bean
 public HasFeatures commonsFeatures() {
   return HasFeatures.abstractFeatures(DiscoveryClient.class, LoadBalancerClient.class);
 }
diff --git a/spring-cloud-commons.xml b/spring-cloud-commons.xml
index 9a0ccc79..b8f11341 100644
--- a/spring-cloud-commons.xml
+++ b/spring-cloud-commons.xml
@@ -8,9 +8,14 @@
 
 
 
-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 ApplicationContext 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).
-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:
+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 ApplicationContext 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).
+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:
 
 
 Java 6 JCE
@@ -22,33 +27,27 @@
 Java 8 JCE
 
 
-Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using).
+Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.
 
-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.
+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.
 
 
 
 Spring Cloud Context: Application Context Services
-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.
+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.
 
The Bootstrap Application Context -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 use bootstrap.yml, -keeping the external configuration for bootstrap and main context -nicely separate. Example: +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 use bootstrap.yml, keeping the external configuration for bootstrap and main context +nicely separate. +The following listing shows an example: bootstrap.yml @@ -60,137 +59,82 @@ nicely separate. Example: uri: ${SPRING_CONFIG_URI:http://localhost:8888} -It is a good idea to set the spring.application.name (in -bootstrap.yml or application.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 your application needs any application-specific configuration from the server, it is a good idea to set the spring.application.name (in bootstrap.yml or application.yml). +You can disable the bootstrap process completely by setting spring.cloud.bootstrap.enabled=false (for example, in system properties).
Application Context Hierarchies -If you build an application context from SpringApplication or -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: +If you build an application context from SpringApplication or 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 contains additional property sources, compared to building the same context without Spring Cloud Config. +The additional property sources are: -"bootstrap": an optional CompositePropertySource appears with high -priority if any PropertySourceLocators are 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. +“bootstrap”: If any PropertySourceLocators are found in the Bootstrap context and if they have non-empty properties, an optional CompositePropertySource appears with high priority. +An example would be properties from the Spring Cloud Config Server. +See “” 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 the application.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. +“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 the application.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 “” 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 ApplicationContext you create, e.g. using its own -interface, or with the SpringApplicationBuilder convenience methods -(parent(), child() and sibling()). 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 spring.application.name 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). -Note that the SpringApplicationBuilder allows you to share an -Environment 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. +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 ApplicationContext you create — for example, by using its own interface or with the SpringApplicationBuilder convenience methods (parent(), child() and sibling()). +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 spring.application.name 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). +Note that the SpringApplicationBuilder lets you share an Environment 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.
Changing the Location of Bootstrap Properties -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 the spring.config.* -variants with the same name, in fact they are used to set up the -bootstrap ApplicationContext by setting those properties in its -Environment. If there is an active profile (from -spring.profiles.active or through the Environment 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 -bootstrap-development.properties for a "development" profile. +The bootstrap.yml (or .properties) location can be specified by setting spring.cloud.bootstrap.name (default: bootstrap) or spring.cloud.bootstrap.location (default: empty) — for example, in System properties. +Those properties behave like the spring.config.* variants with the same name. +In fact, they are used to set up the bootstrap ApplicationContext by setting those properties in its Environment. +If there is an active profile (from spring.profiles.active or through the Environment 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 bootstrap-development.properties for a development profile.
Overriding the Values of Remote Properties -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=true to override with any local -property source, and -spring.cloud.config.overrideSystemProperties=false if only System -properties and env vars should override the remote settings, but not -the local config files. +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. + +
Customizing the Bootstrap Configuration -The bootstrap context can be trained to do anything you like by adding -entries to /META-INF/spring.factories under the key -org.springframework.cloud.bootstrap.BootstrapConfiguration. This is -a comma-separated list of Spring @Configuration 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 @Beans of type -ApplicationContextInitializer. Classes can be marked with an @Order -if you want to control the startup sequence (the default order is -"last"). +The bootstrap context can be set to do anything you like by adding entries to /META-INF/spring.factories under a key named org.springframework.cloud.bootstrap.BootstrapConfiguration. +This holds a comma-separated list of Spring @Configuration 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 @Beans of type ApplicationContextInitializer. +If you want to control the startup sequence, classes can be marked with an @Order annotation (the default order is last). -Be careful when adding custom BootstrapConfiguration that the -classes you add are not @ComponentScanned 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 @ComponentScan or @SpringBootApplication -annotated configuration classes. +When adding custom BootstrapConfiguration, be careful that the classes you add are not @ComponentScanned 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 @ComponentScan or @SpringBootApplication annotated configuration classes. -The bootstrap process ends by injecting initializers into the main -SpringApplication 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 spring.factories and then all @Beans of type -ApplicationContextInitializer are added to the main -SpringApplication before it is started. +The bootstrap process ends by injecting initializers into the main SpringApplication 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 spring.factories. +Then, all @Beans of type ApplicationContextInitializer are added to the main SpringApplication before it is started.
Customizing the Bootstrap Property Sources -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 PropertySourceLocator to the -bootstrap context (via spring.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: +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 PropertySourceLocator to the bootstrap context (through spring.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 { @@ -201,27 +145,15 @@ public class CustomPropertySourceLocator implements PropertySourceLocator { } } -The Environment that is passed in is the one for the -ApplicationContext 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 Environment (e.g. by -keying it on the spring.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.factories containing: +The Environment that is passed in is the one for the ApplicationContext 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 Environment (for example, by keying it on spring.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.factories containing the following, the customProperty PropertySource appears in any application that includes that jar on its classpath: org.springframework.cloud.bootstrap.BootstrapConfiguration=sample.custom.CustomPropertySourceLocator -then the "customProperty" PropertySource will show up in any -application that includes that jar on its classpath.
Environment Changes -The application will listen for an EnvironmentChangeEvent and react -to the change in a couple of standard ways (additional -ApplicationListeners can be added as @Beans by the user in the -normal way). When an EnvironmentChangeEvent is observed it will -have a list of key values that have changed, and the application will -use those to: +The application listens for an EnvironmentChangeEvent and reacts to the change in a couple of standard ways (additional ApplicationListeners can be added as @Beans by the user in the normal way). +When an EnvironmentChangeEvent is observed, it has a list of key values that have changed, and the application uses those to: Re-bind any @ConfigurationProperties beans in the context @@ -230,72 +162,43 @@ use those to: 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 -@Scheduled annotation). If you have a scaled-out client application -then it is better to broadcast the EnvironmentChangeEvent to all -the instances instead of having them polling for changes (e.g. using -the Spring Cloud -Bus). -The EnvironmentChangeEvent covers a large class of refresh use -cases, as long as you can actually make a change to the Environment -and publish the event (those APIs are public and part of core -Spring). You can verify the changes are bound to -@ConfigurationProperties beans by visiting the /configprops -endpoint (normal Spring Boot Actuator feature). For instance a -DataSource can have its maxPoolSize changed at runtime (the -default DataSource created by Spring Boot is an -@ConfigurationProperties bean) and grow capacity -dynamically. Re-binding @ConfigurationProperties 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 -ApplicationContext. To address those concerns we have -@RefreshScope. +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 +@Scheduled annotation). +If you have a scaled-out client application, it is better to broadcast the EnvironmentChangeEvent to all the instances instead of having them polling for changes (for example, by using the Spring Cloud Bus). +The EnvironmentChangeEvent covers a large class of refresh use cases, as long as you can actually make a change to the Environment and publish the event. +Note that those APIs are public and part of core Spring). +You can verify that the changes are bound to @ConfigurationProperties beans by visiting the /configprops endpoint (a normal Spring Boot Actuator feature). +For instance, a DataSource can have its maxPoolSize changed at runtime (the default DataSource created by Spring Boot is an @ConfigurationProperties bean) and grow capacity dynamically. +Re-binding @ConfigurationProperties 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 ApplicationContext. +To address those concerns, we have @RefreshScope.
Refresh Scope -A Spring @Bean that is marked as @RefreshScope 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 DataSource has open -connections when the database URL is changed via the Environment, 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 RefreshScope is 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 -/refresh endpoint (over HTTP or JMX). There is also a refresh(String) method to refresh an -individual bean by name. +When there is a configuration change, a Spring @Bean that is marked as @RefreshScope 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 DataSource has open connections when the database URL is changed via the Environment, 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 RefreshScope is a bean in the context and has a public refreshAll() method to refresh all beans in the scope by clearing the target cache. +The /refresh endpoint exposes this functionality (over HTTP or JMX). +To refresh an individual bean by name, there is also a refresh(String) method. -@RefreshScope works (technically) on an @Configuration -class, but it might lead to surprising behaviour: e.g. it does not -mean that all the @Beans defined 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). +@RefreshScope works (technically) on an @Configuration class, but it might lead to surprising behavior. +For example, it does not mean that all the @Beans defined 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).
Encryption and Decryption -Spring Cloud has an Environment pre-processor for decrypting -property values locally. It follows the same rules as the Config -Server, and has the same external configuration via encrypt.*. 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 the Environment. 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: +Spring Cloud has an Environment pre-processor for decrypting property values locally. +It follows the same rules as the Config Server and has the same external configuration through encrypt.*. +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 the Environment 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. +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: Java 6 JCE @@ -307,46 +210,57 @@ the full strength JCE extensions in your JVM. Java 8 JCE -Extract files into JDK/jre/lib/security folder (whichever version of JRE/JDK x64/x86 you are using). +Extract the files into the JDK/jre/lib/security folder for whichever version of JRE/JDK x64/x86 you use.
Endpoints -For a Spring Boot Actuator application there are some additional management endpoints: +For a Spring Boot Actuator application, some additional management endpoints are available. You can use: -POST to /env to update the Environment and rebind @ConfigurationProperties and log levels +POST to /actuator/env to update the Environment and rebind @ConfigurationProperties and log levels. -/refresh for re-loading the boot strap context and refreshing the @RefreshScope beans +/actuator/refresh to re-load the boot strap context and refresh the @RefreshScope beans. -/restart for closing the ApplicationContext and restarting it (disabled by default) +/actuator/restart to close the ApplicationContext and restart it (disabled by default). -/pause and /resume for calling the Lifecycle methods (stop() and start() on the ApplicationContext) +/actuator/pause and /actuator/resume for calling the Lifecycle methods (stop() and start() on the ApplicationContext).
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 (e.g. discovery via Eureka or Consul). +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).
@EnableDiscoveryClient -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. +Spring Cloud Commons provides the @EnableDiscoveryClient annotation. +This looks for implementations of the DiscoveryClient interface with META-INF/spring.factories. +Implementations of the Discovery Client add a configuration class to spring.factories under the org.springframework.cloud.client.discovery.EnableDiscoveryClient key. +Examples of DiscoveryClient implementations include Spring Cloud Netflix Eureka, Spring Cloud Consul Discovery, and Spring Cloud Zookeeper Discovery. +By default, implementations of DiscoveryClient auto-register the local Spring Boot server with the remote discovery server. +This behavior can be disabled by setting autoRegister=false in @EnableDiscoveryClient. -The use of @EnableDiscoveryClient is no longer required. It is enough to just have a DiscoveryClient implementation -on the classpath to cause the Spring Boot application to register with the service discovery server. +@EnableDiscoveryClient is no longer required. +You can put a DiscoveryClient implementation on the classpath to cause the Spring Boot application to register with the service discovery server.
Health Indicator -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 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.
ServiceRegistry -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. +Commons now provides a ServiceRegistry interface that provides methods such as register(Registration) and deregister(Registration), which let you provide custom registered services. +Registration is a marker interface. +The following example shows the ServiceRegistry in use: @Configuration @EnableDiscoveryClient(autoRegister=false) public class MyConfiguration { @@ -356,7 +270,7 @@ public class MyConfiguration { 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); @@ -365,19 +279,26 @@ public class MyConfiguration { Each ServiceRegistry implementation has its own Registry implementation.
ServiceRegistry Auto-Registration -By default, the ServiceRegistry implementation 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 set spring.cloud.service-registry.auto-registration.enabled=false to disable the behavior via configuration. +By default, the ServiceRegistry implementation 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=false to disable the behavior through configuration.
Service Registry Actuator Endpoint -A /service-registry actuator endpoint is provided by Commons. This endpoint relies on a Registration bean in the Spring Application Context. Calling /service-registry via a GET will return the status of the Registration. A POST to the same endpoint with a JSON body will change the status of the current Registration to the new value. The JSON body has to include the status field with the preferred value. Please see the documentation of the ServiceRegistry 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 UP, DOWN, OUT_OF_SERVICE and UNKNOWN. +Spring Cloud Commons provides a /service-registry actuator endpoint. +This endpoint relies on a Registration bean in the Spring Application Context. +Calling /service-registry with GET returns the status of the Registration. +Using POST to the same endpoint with a JSON body changes the status of the current Registration to the new value. +The JSON body has to include the status field with the preferred value. +Please see the documentation of the ServiceRegistry 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 UP, DOWN, OUT_OF_SERVICE, and UNKNOWN.
Spring RestTemplate as a Load Balancer Client -RestTemplate can be automatically configured to use ribbon. To create a load balanced RestTemplate create a RestTemplate @Bean and use the @LoadBalanced qualifier. - -A RestTemplate bean is no longer created via auto configuration. It must be created by individual applications. - +RestTemplate can be automatically configured to use ribbon. +To create a load-balanced RestTemplate, create a RestTemplate @Bean and use the @LoadBalanced qualifier, as shown in the following example: @Configuration public class MyConfiguration { @@ -397,14 +318,18 @@ public class MyClass { 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 RestTemplate is set up. + +A RestTemplate bean 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 RestTemplate is set up.
Spring WebClient as a Load Balancer Client -WebClient can be automatically configured to use the LoadBalancerClient. To create a load balanced WebClient create a WebClient.Builder @Bean and use the @LoadBalanced qualifier. +WebClient can be automatically configured to use the LoadBalancerClient. +To create a load-balanced WebClient, create a WebClient.Builder @Bean and use the @LoadBalanced qualifier, as shown in the following example: @Configuration public class MyConfiguration { @@ -424,22 +349,18 @@ public class MyClass { .retrieve().bodyToMono(String.class); } } -The URI needs to use a virtual host name (ie. service name, not a host name). +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.
Retrying Failed Requests -A load balanced RestTemplate can 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 balanced RestTemplate 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 spring.cloud.loadbalancer.retry.enabled=false. -The properties you can use are client.ribbon.MaxAutoRetries, -client.ribbon.MaxAutoRetriesNextServer, and client.ribbon.OkToRetryOnAllOperations. -See the Ribbon documentation -for a description of what there properties do. -If you would like to implement a BackOffPolicy in your retries you will need to -create a bean of type LoadBalancedBackOffPolicyFactory, and return the BackOffPolicy -you would like to use for a given service. +A load-balanced RestTemplate can 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-balanced RestTemplate honors some of the Ribbon configuration values related to retrying failed requests. +You can use client.ribbon.MaxAutoRetries, client.ribbon.MaxAutoRetriesNextServer, and client.ribbon.OkToRetryOnAllOperations properties. +If you would like to disable the retry logic with Spring Retry on the classpath, you can set spring.cloud.loadbalancer.retry.enabled=false. +See the Ribbon documentation for a description of what these properties do. +If you would like to implement a BackOffPolicy in your retries, you need to create a bean of type LoadBalancedBackOffPolicyFactory and return the BackOffPolicy you would like to use for a given service, as shown in the following example: @Configuration public class MyConfiguration { @Bean @@ -453,12 +374,11 @@ public class MyConfiguration { } } -client in the above examples should be replaced with your Ribbon client’s -name. +client in the preceding examples should be replaced with your Ribbon client’s name. -If you want to add one or more RetryListener to your retry you will need to +If you want to add one or more RetryListener implementations to your retry functionality, you need to create a bean of type LoadBalancedRetryListenerFactory and return the RetryListener array -you would like to use for a given service. +you would like to use for a given service, as shown in the following example: @Configuration public class MyConfiguration { @Bean @@ -491,12 +411,8 @@ public class MyConfiguration {
Multiple RestTemplate objects -If you want a RestTemplate that is not load balanced, create a RestTemplate -bean and inject it as normal. To access the load balanced RestTemplate use -the @LoadBalanced qualifier when you create your @Bean. - -Notice the @Primary annotation on the plain RestTemplate declaration in the example below, to disambiguate the unqualified @Autowired injection. - +If you want a RestTemplate that is not load-balanced, create a RestTemplate bean and inject it. +To access the load-balanced RestTemplate, use the @LoadBalanced qualifier when you create your @Bean, as shown in the following example:\ @Configuration public class MyConfiguration { @@ -529,13 +445,16 @@ public class MyClass { return restTemplate.getForObject("http://example.com", String.class); } } + +Notice the use of the @Primary annotation on the plain RestTemplate declaration in the preceding example to disambiguate the unqualified @Autowired injection. + -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.$Proxy89 try injecting RestOperations instead or setting spring.aop.proxyTargetClass=true. +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 injecting RestOperations or setting spring.aop.proxyTargetClass=true.
Spring WebFlux WebClient as a Load Balancer Client -WebClient can be configured to use the LoadBalancerClient. A `LoadBalancerExchangeFilterFunction is auto-configured if spring-webflux is on the classpath. +WebClient can be configured to use the LoadBalancerClient. LoadBalancerExchangeFilterFunction is auto-configured if spring-webflux is on the classpath. The following example shows how to configure a WebClient to use load balancer: public class MyClass { @Autowired private LoadBalancerExchangeFilterFunction lbFunction; @@ -550,12 +469,14 @@ public class MyClass { .bodyToMono(String.class); } } -The URI needs to use a virtual host name (ie. service name, not a host name). +The URI needs to use a virtual host name (that is, a service name, not a host name). The LoadBalancerClient is used to create a full physical address.
Ignore Network Interfaces -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". +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 docker0 interface and all interfaces that start with veth: application.yml @@ -567,7 +488,7 @@ The LoadBalancerClient is used to create a full physical addr - veth.* -You can also force to use only specified network addresses using list of regular expressions: +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 @@ -579,43 +500,39 @@ The LoadBalancerClient is used to create a full physical addr - 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 - +You can also force the use of only site-local addresses, as shown in the following example: +.application.yml spring: cloud: inetutils: useOnlySiteLocalInterfaces: true - - +See Inet4Address.html.isSiteLocalAddress() for more details about what constitutes a site-local address.
HTTP Client Factories -Spring Cloud Commons provides beans for creating both Apache HTTP clients (ApacheHttpClientFactory) -as well as OK HTTP clients (OkHttpClientFactory). The OkHttpClientFactory 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, ApacheHttpClientConnectionManagerFactory for the Apache -HTTP client and OkHttpClientConnectionPoolFactory 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 HttpClientBuilder and/or OkHttpClient.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.enabled or spring.cloud.httpclientfactories.ok.enabled to -false. +Spring Cloud Commons provides beans for creating both Apache HTTP clients (ApacheHttpClientFactory) and OK HTTP clients (OkHttpClientFactory). +The OkHttpClientFactory 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: ApacheHttpClientConnectionManagerFactory for the Apache HTTP client and OkHttpClientConnectionPoolFactory 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 HttpClientBuilder or OkHttpClient.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 setting spring.cloud.httpclientfactories.apache.enabled or spring.cloud.httpclientfactories.ok.enabled to false.
Enabled Features -A /features 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. +Spring Cloud Commons provides a /features 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.
Feature types 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, LoadBalancerClient or LockService. The abstract class or interface is used to find a bean of that type in the context. The version displayed is bean.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. +Abstract features are features where an interface or abstract class is defined and that an implementation the creates, such as DiscoveryClient, LoadBalancerClient, or LockService. +The abstract class or interface is used to find a bean of that type in the context. +The version displayed is bean.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.
Declaring features -Any module can declare any number of HasFeature beans. Some examples: +Any module can declare any number of HasFeature beans, as shown in the following examples: @Bean public HasFeatures commonsFeatures() { return HasFeatures.abstractFeatures(DiscoveryClient.class, LoadBalancerClient.class);