1. Spring Boot -
A Microframework for
Microservices
Nilanjan Roy
2. What is Spring Boot ?
• Focuses attention at a single point (as opposed to large
collection of spring-* projects)
• A tool for getting started very quickly with Spring
• Common non-functional requirements for a "real" application
• Exposes a lot of useful features by default
• Gets out of the way quickly if you want to change defaults
4. How Does it help microservices ?
• You are going to write more than one microservice
• That means you are going to do this a lot….
– Declare dependencies
– Configure Spring
– Configure logging
– Load properties file
– Setup monitoring
– Add Security
– Talk to a database
– Add metrics
6. Spring Boot Modules
• Spring Boot - main library supporting the other parts of Spring Boot
• Spring Boot Autoconfigure -
single @EnableAutoConfiguration annotation creates a whole Spring
context
• Spring Boot Starters - a set of convenient dependency descriptors that
you can include in your application.
• Spring Boot CLI - compiles and runs Groovy source as a Spring
application
• Spring Boot Actuator - common non-functional features that make an
app instantly deployable and supportable in production
• Spring Boot Tools - for building and executing self-contained JAR and
WAR archives
• Spring Boot Samples - a wide range of sample apps
9. Gaining application insight with
Actuator
• Spring Boot Actuator adds several helpful management endpoints
to a Spring Boot-based application. These endpoints include
• GET /autoconfig —Explains the decisions made by Spring Boot when
applying autoconfiguration
• GET /beans —Catalogs the beans that are configured for the running
application
• GET /configprops —Lists all properties available for configuring the
properties of beans in the application with their current values
• GET /dump —Lists application threads, including a stack trace for
each thread
10. Gaining application insight with
the Actuator
• GET /env —Lists all environment and system property variables available to
the application context
• GET /env/{name} —Displays the value for a specific environment or
property variable
• GET /health —Displays the current application health
• GET /info —Displays application-specific information
• GET /metrics —Lists metrics concerning the application, including running
counts of requests against certain endpoints
• GET /metrics/{name} —Displays metrics for a specific application metric
key
• POST /shutdown —Forcibly shuts down the application
• GET /trace —Lists metadata concerning recent requests served through the
application, including request and response headers
15. Customizing Monitoring Endpoints
• We can change how those endpoints are exposed
using application.properties
– management.port=8081 - you can expose those endpoints on port
other than the one application is using .
– management.address=127.0.0.1 - you can only allow to access by IP
address (localhost here).
– management.context-path=/actuator - allows you to have those
endpoints grouped under specified context path rather than root,
i.e. /actuator/health.
– endpoints.health.enabled=false - allows to enable/disable specified
endpoint by name, here /health is disabled.
16. Customizing Monitoring Endpoints
• We can change if an endpoint is enabled, if it is considered sensitive and even
its id.
• Following entry in the application.properties that changes the sensitivity and id
of the beans endpoint and also enables shutdown.
endpoints.beans.id=springbeans
endpoints.beans.sensitive=false
endpoints.shutdown.enabled=true
• By default, all endpoints except for shutdown are enabled. If you prefer to
specifically “opt-in” endpoint enablement you can use
the endpoints.enabled property. For example, the following will
disable all endpoints except for info:
endpoints.enabled=false
endpoints.info.enabled=true
17. Securing Monitoring Endpoints
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
• Disable basic security in application.properties, so that it leaves only the
sensitive Actuator endpoints secured and leaves the rest open for access:
– security.basic.enabled=false
• Set up a new username, or a password if you don't want it to be different on
each start:
– security.user.name=admin
– security.user.password=new_password
• In case you're using the security features across the application and decided to
secure those endpoints yourself, you can disable default security for Actuator:
– management.security.enabled=false
18. Custom Healthchecks
• Besides checking if the application is UP or DOWN, which is done by
default, you can add checks for things like database connectivity or MQ
status etc.
@Component
public class MyHealth implements HealthIndicator {
@Override
public Health health() {
int errorCode = check(); // perform some specific health check
if (errorCode != 0)
{
return Health.down().withDetail("Error Code",
errorCode).build();
}
return Health.up().build();
}
}
20. Emitting your own Metrics
• GaugeService :
– A service that can be used to submit a named double value for storage
and analysis.
– For instance, the value submitted here could be a method execution
timing result, and it would go to a backend that keeps a histogram of
recent values for comparison purposes.
• CounterService :
– Increment , decrement or reset an integer value (e.g. number of times
an error was thrown)
23. Logging with Spring Boot
• Spring Boot uses Commons Logging for all internal logging, but
leaves the underlying log implementation open. Default
configurations are provided for Java Util Logging,Log4J and Logback.
In each case there is console output and file output (rotating, 10
Mb file size).
• By default, If we use the ‘Starter POMs’, Logback will be used for
logging. Appropriate Logback routing is also included to ensure that
dependent libraries that use Java Util Logging, Commons Logging,
Log4J or SLF4J will all work correctly.
24. Spring Boot AutoConfiguration
• Spring Boot auto-configuration attempts to automatically configure your
Spring application based on the jar dependencies that you have added.
For example, If HSQLDB is on your classpath, and you have not manually
configured any database connection beans, then it will auto-configure an
in-memory database.
• You need to opt-in to auto-configuration by adding
the @EnableAutoConfiguration or @SpringBootApplication annotations to
one of your @Configurationclasses.
• Disabling AutoConfiguration
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration { }
26. Behind the Scene
• There are two parts to it :
1) List of files which has to be considered as
configuration classes
2) When these should be applied
27. Behind the Scene
• @EnableAutoConfiguration" is a spring-boot(autoconfigure) annotation
which is handled by
org.springframework.boot.autoconfigure.EnableAutoConfigurationImport
Selector.
• In "EnableAutoConfigurationImportSelector", it uses
"org.springframework.core.io.support.SpringFactoriesLoader#loadFactory
Names" from spring-core to load configurations whose key is
"org.springframework.boot.autoconfigure.EnableAutoConfiguration".
• This method reads "META-INF/spring.factories" from jar files.(multiple jar
files can have "spring.factories" and when they have same key, comma
delimited values will be merged.)
30. Understand “Twelve-Factor App”
style configuration
• Spring Boot builds upon propertySource
• It allows you to externalize your configuration so you can work with the
same application code in different environments. You can use properties
files, YAML files, environment variables and command-line arguments to
externalize configuration.
• Spring Boot uses a very particular PropertySource order that is designed
to allow sensible overriding of values, properties are considered in the
following order:
32. Understand “Twelve-Factor App”
style configuration
Set the active Spring profiles :
• Profile-specific application properties outside of your packaged jar
(application-{profile}.properties and YAML variants)
• Profile-specific application properties packaged inside your jar
(application-{profile}.properties and YAML variants)
– Usually set through system profile (spring.profiles.active) or an OS environment variable
(SPRING_PROFILES_ACTIVE).
e.g. $ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar
or it can be set in application.properties :
spring.profiles.active=production
35. Common application properties
• http://docs.spring.io/spring-
boot/docs/current/reference/html/common-
application-properties.html
36. Understand “Twelve-Factor App”
style configuration
• @ConfigurationProperties
– A way to map properties to POJO
– Type Safe
– IDE Support
– Can be validated with @Valid