SlideShare une entreprise Scribd logo
1  sur  45
Télécharger pour lire hors ligne
Joris Kuipers
@jkuipers
Boot Loot!
About Me
 Joris Kuipers
 @jkuipers
 CTO,
hands-on architect and
fly-by-night Spring trainer
@ Trifork Amsterdam
What’s In The Box?
 Tips & tricks for Boot applications
 Based on production experience
 And too much time spent w/ Spring
 Up your game and
Spring like the pros!
Spring-MVC Default Errors
“It is a true man's part not to err, but it is also noble of a man
to perceive his error.”
― Apollonius of Tyana
Spring Boot Default Error Page
 Rendered for uncaught exceptions
 Browsers: HTML, other HTTP clients: JSON
 Let’s look at default for binding/validation
errors from MVC Controllers
What’s Happening?
 Binding-/validation errors cause FieldErrors
 extending DefaultMessageSourceResolvable
 which are marshalled as-is
Wouldn’t It Be Nice…
 … if these error codes were in fact resolved?
 Solution: custom ErrorAttributes
Using Custom
@ConfigurationProperties
“Custom is second nature”
― Saint Augustine
@ConfigurationProperties
 Boot-feature to bind config values to Java bean
 For config keys sharing common prefix
 Consume through dependency injection
 Let’s look at an example
 Groups related properties, easy access
 Nice, but just like @Value("${loot.game}")
 IDE Support
 Validation
Let’s have a look
Benefits
@ConfigurationProperties summary
 Discovering available configuration
 Especially nice in big projects
 or when using shared libraries with auto-
configuration
 Validating configuration
 Exposed by /configprops actuator endpoint
 Will be auto-scanned in Boot 2.2
What About Relaxed Binding?
 E.g. loot.allow-transfer or
LOOT_ALLOW_TRANSFER for
allowTransfer property
 Required configuration properties
with Boot 1.x
 Since Boot 2, works everywhere
 By using kebab casing
 @Value("${loot.allow-transfer}")
Reducing Metrics Cardinality
“For the wise man looks into space and he knows
there is no limited dimensions.”
― Zhuangzi
Micrometer.io Metrics
 Boot apps can collect & expose metrics
 Metric: value + associated key-values
 Dimensions / tags
 Example: http.client.requests
 Timer, plus info on HTTP method, status, URI, etc.
Dimension Cardinality
 Single dimension can have multiple values
 Not useful if range is too big
 Won’t even work
 Let’s look at an example
Reducing Dimension Cardinality
 First of all: use APIs as intended
 E.g. RestTemplate with URI Template variables
 However, not always possible / the solution
 Micrometer API allows post-processing filters
 Inspect and change tag values to limit nr of
options
Builders and Customizers
“Believe me, that was a happy age, before the days of architects,
before the days of builders.”
― Lucius Annaeus Seneca
Spring Boot Builders
 Many common helpers in Spring apps
 RestTemplate, Jackson ObjectMappers, …
 Often created in code or @Bean methods directly
@Bean
RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
// ...
return restTemplate;
}
Contributing Instrumentation
 Spring frameworks or custom libraries often
need to instrument code
 RestTemplate interceptors for metrics, distributed
tracing or service discovery
 MockMvc setup for Security or RestDocs support
 How to apply dynamically to all instances?
Builders and Customizers
 Common pattern: create a builder
 Autoconfigured singleton Spring Bean
 Inject builder with customizers
 Other beans, wired by type
 Contribute configuration: either on the builder or
on the result of the builder
 Use the builder to get instance of helper
Opiniated Builders
 Builders can provide own default config
 Allows Boot-specific opiniated defaults
 And additional auto-configuration
 Examples:
 Jackson ObjectMapper ignores unknown fields,
registers modules
 RestTemplate using Apache or “Ok” HTTP client
Builder Example:
RestTemplateBuilder
 Set up in RestTemplateAutoConfiguration
 Injected with RestTemplateCustomizers
 Which are provided by many frameworks
 E.g. micrometer.io integration, Spring Cloud
 Let’s see this in action
But what about…
 Sleuth distributed tracing?
 That works without builder!
 Uses BeanPostProcessor to register
interceptor
 Works for this case, not generic solution
 E.g. target might be immutable
 Still requires RestTemplate to be a Spring bean
Customizer Examples
 Jackson OffsetDateTime marshalling
@Bean
Jackson2ObjectMapperBuilderCustomizer offsetDateTimeSerializerCustomizer() {
return objectMapperBuilder -> objectMapperBuilder.serializerByType(
OffsetDateTime.class,
new JsonSerializer<OffsetDateTime>() {
public void serialize(OffsetDateTime value, JsonGenerator generator,
SerializerProvider sp) throws IOException {
generator.writeString(
value.truncatedTo(SECONDS).format(ISO_OFFSET_DATE_TIME));
}
});
}
Local Developer Configuration
“We believe in global scalability with local relevance.”
― Gillian Tans
Local Development Configuration
 Setup for local development often differs
 Different config properties
 Security disabled, or with hardcoded users
 No cloud-based services
 How to ensure easy setup for all devs?
“Local” Spring Profile
 Solution: define “local” Spring profile
 Specific configuration files
 E.g. application-local.properties
 Local-specific Spring beans configuration
How to enable “local” profile
 Typical way to enable profiles:
spring.profiles.active property
 Comma-separated list
 Must be active for all local services
 Per-service run config is tedious and error-prone
 Solution: use OS environment variable!
 SPRING_PROFILES_ACTIVE
Orthogonal Profiles
 What if you want to use other profiles as well?
 Can’t use two different spring.profiles.active
properties
 Will override, not merge
 Solution: use SPRING_PROFILES_INCLUDE env var
 Binds to spring.profiles.include
 Will add, not override
Examples of Local Config
 Unique port(s) per service
 Connection settings
 Security
 Actuator web endpoints enabling / config
 Disabling micrometer.io metrics bindings
 Disabling Spring Cloud central configuration
Local Logging Setup
Through application-local.properties:
 Hide some of the Sleuth noise
logging.pattern.level=%5p [%X{traceId:-}]
 Change log levels for development
logging.level.org.springframework.ws.client.
MessageTracing=TRACE
Adding external directories to
fat JAR’s classpath
“But we try to pretend, you see, that the external world exists
altogether independently of us.”
― Alan Watts
External Classpath Resources
 Non-Boot apps often read resources from
external classpath directories
 Config files, keystores, resource bundles, …
 Allows for easy updating on the one hand
 And location-transparency in code on the
other
External Classpath Dirs
with Spring Boot
 Becomes a problem when
migrating to Boot’s fat jar
 Classpath only within jar
 Lots of work to rewrite all code (incl. libs)
Spring Boot Launchers
 Boot apps use a launcher
 Default launcher can be overridden
 Configure layout through build plugin
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<layout>ZIP</layout>
</configuration>
</plugin>
PropertiesLauncher
 Configured as Main-Class in MANIFEST.MF
 Loads settings from a loader.properties,
manifest or environment variables
 Supports adding directories to the classpath
 Via loader.path property
Conclusion
 Boot is awesome
 Doesn’t mean just use as-is
 Plenty of customization options
 It pays off to read documentation and
visit Spring conferences ;)
 https://github.com/jkuipers/bootloot
We’re Hiring!
Joris Kuipers
@jkuipers
Thanks!
Q&A
Bonus contents (wait, there’s more?)
Custom Auto-configuration
“Sometimes, magic is just someone spending more time on
something than anyone else might reasonably expect.”
― Teller
Auto-Configuration
 Best known Spring Boot feature
 Condition configuration classes, evaluated at
startup
 After your own config classes
 Can be great for custom libraries as well
 Micro-services
 Inter-project
Write Your Own Auto-Configuration
 Create a Java library
 Add one or more @Configuration classes
 List them in a META-INF/spring.factories file
 Under key
org.springframework.boot.autoconfigure.
EnableAutoConfiguration
Examples
 Logging
 MDC setup, Sleuth overrides
 Metrics
 Shared custom tags, cardinality reduction filters, exposing
trace IDs in responses, accepting external trace IDs
 HTTP Client
 Custom HTTP client setup, RestTemplate setup
 MVC
 Custom ErrorAttributes, shared ControllerAdvice
Caveats
 Consider interaction with Boot’s auto-config
 Use @AutoConfigureBefore/-After where needed
 Allow overrides and disabling selectively

Contenu connexe

Tendances

Weaveworks at AWS re:Invent 2016: Operations Management with Amazon ECS
Weaveworks at AWS re:Invent 2016: Operations Management with Amazon ECSWeaveworks at AWS re:Invent 2016: Operations Management with Amazon ECS
Weaveworks at AWS re:Invent 2016: Operations Management with Amazon ECSWeaveworks
 
(SEC308) Navigating PCI Compliance in the Cloud | AWS re:Invent 2014
(SEC308) Navigating PCI Compliance in the Cloud | AWS re:Invent 2014(SEC308) Navigating PCI Compliance in the Cloud | AWS re:Invent 2014
(SEC308) Navigating PCI Compliance in the Cloud | AWS re:Invent 2014Amazon Web Services
 
Serverless Apps with Open Whisk
Serverless Apps with Open Whisk Serverless Apps with Open Whisk
Serverless Apps with Open Whisk Dev_Events
 
Intro to Batch Processing on AWS - DevDay Austin 2017
Intro to Batch Processing on AWS - DevDay Austin 2017Intro to Batch Processing on AWS - DevDay Austin 2017
Intro to Batch Processing on AWS - DevDay Austin 2017Amazon Web Services
 
Spring Security Patterns
Spring Security PatternsSpring Security Patterns
Spring Security PatternsVMware Tanzu
 
Continuous Delivery to Amazon ECS
Continuous Delivery to Amazon ECSContinuous Delivery to Amazon ECS
Continuous Delivery to Amazon ECSAmazon Web Services
 
What you see is what you get for AWS infrastructure
What you see is what you get for AWS infrastructureWhat you see is what you get for AWS infrastructure
What you see is what you get for AWS infrastructureAnton Babenko
 
Getting Started with Docker on AWS - DevDay Austin 2017
Getting Started with Docker on AWS - DevDay Austin 2017Getting Started with Docker on AWS - DevDay Austin 2017
Getting Started with Docker on AWS - DevDay Austin 2017Amazon Web Services
 
Kubernetes your next application server
Kubernetes  your next application serverKubernetes  your next application server
Kubernetes your next application serverRed Hat Developers
 
Building and Scaling a Containerized Microservice - DevDay Austin 2017
Building and Scaling a Containerized Microservice - DevDay Austin 2017Building and Scaling a Containerized Microservice - DevDay Austin 2017
Building and Scaling a Containerized Microservice - DevDay Austin 2017Amazon Web Services
 
(APP309) Running and Monitoring Docker Containers at Scale | AWS re:Invent 2014
(APP309) Running and Monitoring Docker Containers at Scale | AWS re:Invent 2014(APP309) Running and Monitoring Docker Containers at Scale | AWS re:Invent 2014
(APP309) Running and Monitoring Docker Containers at Scale | AWS re:Invent 2014Amazon Web Services
 
(CMP406) Amazon ECS at Coursera: A general-purpose microservice
(CMP406) Amazon ECS at Coursera: A general-purpose microservice(CMP406) Amazon ECS at Coursera: A general-purpose microservice
(CMP406) Amazon ECS at Coursera: A general-purpose microserviceAmazon Web Services
 
[AWS Dev Day] 앱 현대화 | AWS Fargate를 사용한 서버리스 컨테이너 활용 하기 - 삼성전자 개발자 포털 사례 - 정영준...
[AWS Dev Day] 앱 현대화 | AWS Fargate를 사용한 서버리스 컨테이너 활용 하기 - 삼성전자 개발자 포털 사례 - 정영준...[AWS Dev Day] 앱 현대화 | AWS Fargate를 사용한 서버리스 컨테이너 활용 하기 - 삼성전자 개발자 포털 사례 - 정영준...
[AWS Dev Day] 앱 현대화 | AWS Fargate를 사용한 서버리스 컨테이너 활용 하기 - 삼성전자 개발자 포털 사례 - 정영준...Amazon Web Services Korea
 
Continuous Delivery with Docker and Amazon ECS
Continuous Delivery with Docker and Amazon ECSContinuous Delivery with Docker and Amazon ECS
Continuous Delivery with Docker and Amazon ECSAmazon Web Services
 
Building a Serverless company with Node.js, React and the Serverless Framewor...
Building a Serverless company with Node.js, React and the Serverless Framewor...Building a Serverless company with Node.js, React and the Serverless Framewor...
Building a Serverless company with Node.js, React and the Serverless Framewor...Luciano Mammino
 
"AWS Fargate: Containerization meets Serverless" at AWS User Group Cologne 20...
"AWS Fargate: Containerization meets Serverless" at AWS User Group Cologne 20..."AWS Fargate: Containerization meets Serverless" at AWS User Group Cologne 20...
"AWS Fargate: Containerization meets Serverless" at AWS User Group Cologne 20...Vadym Kazulkin
 
Getting Started with Docker On AWS
Getting Started with Docker On AWSGetting Started with Docker On AWS
Getting Started with Docker On AWSAmazon Web Services
 
EKS security best practices
EKS security best practicesEKS security best practices
EKS security best practicesJohn Varghese
 

Tendances (20)

Docker and java
Docker and javaDocker and java
Docker and java
 
Weaveworks at AWS re:Invent 2016: Operations Management with Amazon ECS
Weaveworks at AWS re:Invent 2016: Operations Management with Amazon ECSWeaveworks at AWS re:Invent 2016: Operations Management with Amazon ECS
Weaveworks at AWS re:Invent 2016: Operations Management with Amazon ECS
 
(SEC308) Navigating PCI Compliance in the Cloud | AWS re:Invent 2014
(SEC308) Navigating PCI Compliance in the Cloud | AWS re:Invent 2014(SEC308) Navigating PCI Compliance in the Cloud | AWS re:Invent 2014
(SEC308) Navigating PCI Compliance in the Cloud | AWS re:Invent 2014
 
Serverless Apps with Open Whisk
Serverless Apps with Open Whisk Serverless Apps with Open Whisk
Serverless Apps with Open Whisk
 
Intro to Batch Processing on AWS - DevDay Austin 2017
Intro to Batch Processing on AWS - DevDay Austin 2017Intro to Batch Processing on AWS - DevDay Austin 2017
Intro to Batch Processing on AWS - DevDay Austin 2017
 
Spring Security Patterns
Spring Security PatternsSpring Security Patterns
Spring Security Patterns
 
Continuous Delivery to Amazon ECS
Continuous Delivery to Amazon ECSContinuous Delivery to Amazon ECS
Continuous Delivery to Amazon ECS
 
What you see is what you get for AWS infrastructure
What you see is what you get for AWS infrastructureWhat you see is what you get for AWS infrastructure
What you see is what you get for AWS infrastructure
 
Getting Started with Docker on AWS - DevDay Austin 2017
Getting Started with Docker on AWS - DevDay Austin 2017Getting Started with Docker on AWS - DevDay Austin 2017
Getting Started with Docker on AWS - DevDay Austin 2017
 
Kubernetes your next application server
Kubernetes  your next application serverKubernetes  your next application server
Kubernetes your next application server
 
Advanced Container Scheduling
Advanced Container SchedulingAdvanced Container Scheduling
Advanced Container Scheduling
 
Building and Scaling a Containerized Microservice - DevDay Austin 2017
Building and Scaling a Containerized Microservice - DevDay Austin 2017Building and Scaling a Containerized Microservice - DevDay Austin 2017
Building and Scaling a Containerized Microservice - DevDay Austin 2017
 
(APP309) Running and Monitoring Docker Containers at Scale | AWS re:Invent 2014
(APP309) Running and Monitoring Docker Containers at Scale | AWS re:Invent 2014(APP309) Running and Monitoring Docker Containers at Scale | AWS re:Invent 2014
(APP309) Running and Monitoring Docker Containers at Scale | AWS re:Invent 2014
 
(CMP406) Amazon ECS at Coursera: A general-purpose microservice
(CMP406) Amazon ECS at Coursera: A general-purpose microservice(CMP406) Amazon ECS at Coursera: A general-purpose microservice
(CMP406) Amazon ECS at Coursera: A general-purpose microservice
 
[AWS Dev Day] 앱 현대화 | AWS Fargate를 사용한 서버리스 컨테이너 활용 하기 - 삼성전자 개발자 포털 사례 - 정영준...
[AWS Dev Day] 앱 현대화 | AWS Fargate를 사용한 서버리스 컨테이너 활용 하기 - 삼성전자 개발자 포털 사례 - 정영준...[AWS Dev Day] 앱 현대화 | AWS Fargate를 사용한 서버리스 컨테이너 활용 하기 - 삼성전자 개발자 포털 사례 - 정영준...
[AWS Dev Day] 앱 현대화 | AWS Fargate를 사용한 서버리스 컨테이너 활용 하기 - 삼성전자 개발자 포털 사례 - 정영준...
 
Continuous Delivery with Docker and Amazon ECS
Continuous Delivery with Docker and Amazon ECSContinuous Delivery with Docker and Amazon ECS
Continuous Delivery with Docker and Amazon ECS
 
Building a Serverless company with Node.js, React and the Serverless Framewor...
Building a Serverless company with Node.js, React and the Serverless Framewor...Building a Serverless company with Node.js, React and the Serverless Framewor...
Building a Serverless company with Node.js, React and the Serverless Framewor...
 
"AWS Fargate: Containerization meets Serverless" at AWS User Group Cologne 20...
"AWS Fargate: Containerization meets Serverless" at AWS User Group Cologne 20..."AWS Fargate: Containerization meets Serverless" at AWS User Group Cologne 20...
"AWS Fargate: Containerization meets Serverless" at AWS User Group Cologne 20...
 
Getting Started with Docker On AWS
Getting Started with Docker On AWSGetting Started with Docker On AWS
Getting Started with Docker On AWS
 
EKS security best practices
EKS security best practicesEKS security best practices
EKS security best practices
 

Similaire à Boot Loot

Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Gunith Devasurendra
 
IBM ConnectED 2015 - MAS103 XPages Performance and Scalability
IBM ConnectED 2015 - MAS103 XPages Performance and ScalabilityIBM ConnectED 2015 - MAS103 XPages Performance and Scalability
IBM ConnectED 2015 - MAS103 XPages Performance and ScalabilityPaul Withers
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfAppster1
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfAppster1
 
Spring training
Spring trainingSpring training
Spring trainingTechFerry
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang YoonJesang Yoon
 
Gain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring BatchGain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring BatchInexture Solutions
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS BackendLaurent Cerveau
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellPVS-Studio
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your CodeNate Abele
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0Nate Abele
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial EnAnkur Dongre
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Pythongturnquist
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullySpringPeople
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchMats Bryntse
 

Similaire à Boot Loot (20)

Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
IBM ConnectED 2015 - MAS103 XPages Performance and Scalability
IBM ConnectED 2015 - MAS103 XPages Performance and ScalabilityIBM ConnectED 2015 - MAS103 XPages Performance and Scalability
IBM ConnectED 2015 - MAS103 XPages Performance and Scalability
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
 
Spring training
Spring trainingSpring training
Spring training
 
Spring boot
Spring bootSpring boot
Spring boot
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoon
 
Persistence
PersistencePersistence
Persistence
 
Gain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring BatchGain Proficiency in Batch Processing with Spring Batch
Gain Proficiency in Batch Processing with Spring Batch
 
Elements for an iOS Backend
Elements for an iOS BackendElements for an iOS Backend
Elements for an iOS Backend
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShell
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Intro To Spring Python
Intro To Spring PythonIntro To Spring Python
Intro To Spring Python
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium Successfully
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 

Plus de Joris Kuipers

Action Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot ApplicationsAction Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot ApplicationsJoris Kuipers
 
Hearts Of Darkness - a Spring DevOps Apocalypse
Hearts Of Darkness - a Spring DevOps ApocalypseHearts Of Darkness - a Spring DevOps Apocalypse
Hearts Of Darkness - a Spring DevOps ApocalypseJoris Kuipers
 
I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...Joris Kuipers
 
Day 2 Problems in CQRS & Event Sourcing
Day 2 Problems in CQRS & Event SourcingDay 2 Problems in CQRS & Event Sourcing
Day 2 Problems in CQRS & Event SourcingJoris Kuipers
 
Building Layers of Defense with Spring Security
Building Layers of Defense with Spring SecurityBuilding Layers of Defense with Spring Security
Building Layers of Defense with Spring SecurityJoris Kuipers
 
Come Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with FlywayCome Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with FlywayJoris Kuipers
 

Plus de Joris Kuipers (6)

Action Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot ApplicationsAction Jackson! Effective JSON processing in Spring Boot Applications
Action Jackson! Effective JSON processing in Spring Boot Applications
 
Hearts Of Darkness - a Spring DevOps Apocalypse
Hearts Of Darkness - a Spring DevOps ApocalypseHearts Of Darkness - a Spring DevOps Apocalypse
Hearts Of Darkness - a Spring DevOps Apocalypse
 
I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...I Can See Clearly Now - Observing & understanding your Spring applications at...
I Can See Clearly Now - Observing & understanding your Spring applications at...
 
Day 2 Problems in CQRS & Event Sourcing
Day 2 Problems in CQRS & Event SourcingDay 2 Problems in CQRS & Event Sourcing
Day 2 Problems in CQRS & Event Sourcing
 
Building Layers of Defense with Spring Security
Building Layers of Defense with Spring SecurityBuilding Layers of Defense with Spring Security
Building Layers of Defense with Spring Security
 
Come Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with FlywayCome Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with Flyway
 

Dernier

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 

Dernier (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 

Boot Loot

  • 2. About Me  Joris Kuipers  @jkuipers  CTO, hands-on architect and fly-by-night Spring trainer @ Trifork Amsterdam
  • 3. What’s In The Box?  Tips & tricks for Boot applications  Based on production experience  And too much time spent w/ Spring  Up your game and Spring like the pros!
  • 4. Spring-MVC Default Errors “It is a true man's part not to err, but it is also noble of a man to perceive his error.” ― Apollonius of Tyana
  • 5. Spring Boot Default Error Page  Rendered for uncaught exceptions  Browsers: HTML, other HTTP clients: JSON  Let’s look at default for binding/validation errors from MVC Controllers
  • 6. What’s Happening?  Binding-/validation errors cause FieldErrors  extending DefaultMessageSourceResolvable  which are marshalled as-is
  • 7. Wouldn’t It Be Nice…  … if these error codes were in fact resolved?  Solution: custom ErrorAttributes
  • 8. Using Custom @ConfigurationProperties “Custom is second nature” ― Saint Augustine
  • 9. @ConfigurationProperties  Boot-feature to bind config values to Java bean  For config keys sharing common prefix  Consume through dependency injection  Let’s look at an example
  • 10.  Groups related properties, easy access  Nice, but just like @Value("${loot.game}")  IDE Support  Validation Let’s have a look Benefits
  • 11. @ConfigurationProperties summary  Discovering available configuration  Especially nice in big projects  or when using shared libraries with auto- configuration  Validating configuration  Exposed by /configprops actuator endpoint  Will be auto-scanned in Boot 2.2
  • 12. What About Relaxed Binding?  E.g. loot.allow-transfer or LOOT_ALLOW_TRANSFER for allowTransfer property  Required configuration properties with Boot 1.x  Since Boot 2, works everywhere  By using kebab casing  @Value("${loot.allow-transfer}")
  • 13. Reducing Metrics Cardinality “For the wise man looks into space and he knows there is no limited dimensions.” ― Zhuangzi
  • 14. Micrometer.io Metrics  Boot apps can collect & expose metrics  Metric: value + associated key-values  Dimensions / tags  Example: http.client.requests  Timer, plus info on HTTP method, status, URI, etc.
  • 15. Dimension Cardinality  Single dimension can have multiple values  Not useful if range is too big  Won’t even work  Let’s look at an example
  • 16. Reducing Dimension Cardinality  First of all: use APIs as intended  E.g. RestTemplate with URI Template variables  However, not always possible / the solution  Micrometer API allows post-processing filters  Inspect and change tag values to limit nr of options
  • 17. Builders and Customizers “Believe me, that was a happy age, before the days of architects, before the days of builders.” ― Lucius Annaeus Seneca
  • 18. Spring Boot Builders  Many common helpers in Spring apps  RestTemplate, Jackson ObjectMappers, …  Often created in code or @Bean methods directly @Bean RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); // ... return restTemplate; }
  • 19. Contributing Instrumentation  Spring frameworks or custom libraries often need to instrument code  RestTemplate interceptors for metrics, distributed tracing or service discovery  MockMvc setup for Security or RestDocs support  How to apply dynamically to all instances?
  • 20. Builders and Customizers  Common pattern: create a builder  Autoconfigured singleton Spring Bean  Inject builder with customizers  Other beans, wired by type  Contribute configuration: either on the builder or on the result of the builder  Use the builder to get instance of helper
  • 21. Opiniated Builders  Builders can provide own default config  Allows Boot-specific opiniated defaults  And additional auto-configuration  Examples:  Jackson ObjectMapper ignores unknown fields, registers modules  RestTemplate using Apache or “Ok” HTTP client
  • 22. Builder Example: RestTemplateBuilder  Set up in RestTemplateAutoConfiguration  Injected with RestTemplateCustomizers  Which are provided by many frameworks  E.g. micrometer.io integration, Spring Cloud  Let’s see this in action
  • 23. But what about…  Sleuth distributed tracing?  That works without builder!  Uses BeanPostProcessor to register interceptor  Works for this case, not generic solution  E.g. target might be immutable  Still requires RestTemplate to be a Spring bean
  • 24. Customizer Examples  Jackson OffsetDateTime marshalling @Bean Jackson2ObjectMapperBuilderCustomizer offsetDateTimeSerializerCustomizer() { return objectMapperBuilder -> objectMapperBuilder.serializerByType( OffsetDateTime.class, new JsonSerializer<OffsetDateTime>() { public void serialize(OffsetDateTime value, JsonGenerator generator, SerializerProvider sp) throws IOException { generator.writeString( value.truncatedTo(SECONDS).format(ISO_OFFSET_DATE_TIME)); } }); }
  • 25. Local Developer Configuration “We believe in global scalability with local relevance.” ― Gillian Tans
  • 26. Local Development Configuration  Setup for local development often differs  Different config properties  Security disabled, or with hardcoded users  No cloud-based services  How to ensure easy setup for all devs?
  • 27. “Local” Spring Profile  Solution: define “local” Spring profile  Specific configuration files  E.g. application-local.properties  Local-specific Spring beans configuration
  • 28. How to enable “local” profile  Typical way to enable profiles: spring.profiles.active property  Comma-separated list  Must be active for all local services  Per-service run config is tedious and error-prone  Solution: use OS environment variable!  SPRING_PROFILES_ACTIVE
  • 29. Orthogonal Profiles  What if you want to use other profiles as well?  Can’t use two different spring.profiles.active properties  Will override, not merge  Solution: use SPRING_PROFILES_INCLUDE env var  Binds to spring.profiles.include  Will add, not override
  • 30. Examples of Local Config  Unique port(s) per service  Connection settings  Security  Actuator web endpoints enabling / config  Disabling micrometer.io metrics bindings  Disabling Spring Cloud central configuration
  • 31. Local Logging Setup Through application-local.properties:  Hide some of the Sleuth noise logging.pattern.level=%5p [%X{traceId:-}]  Change log levels for development logging.level.org.springframework.ws.client. MessageTracing=TRACE
  • 32. Adding external directories to fat JAR’s classpath “But we try to pretend, you see, that the external world exists altogether independently of us.” ― Alan Watts
  • 33. External Classpath Resources  Non-Boot apps often read resources from external classpath directories  Config files, keystores, resource bundles, …  Allows for easy updating on the one hand  And location-transparency in code on the other
  • 34. External Classpath Dirs with Spring Boot  Becomes a problem when migrating to Boot’s fat jar  Classpath only within jar  Lots of work to rewrite all code (incl. libs)
  • 35. Spring Boot Launchers  Boot apps use a launcher  Default launcher can be overridden  Configure layout through build plugin <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <layout>ZIP</layout> </configuration> </plugin>
  • 36. PropertiesLauncher  Configured as Main-Class in MANIFEST.MF  Loads settings from a loader.properties, manifest or environment variables  Supports adding directories to the classpath  Via loader.path property
  • 37. Conclusion  Boot is awesome  Doesn’t mean just use as-is  Plenty of customization options  It pays off to read documentation and visit Spring conferences ;)  https://github.com/jkuipers/bootloot
  • 40. Bonus contents (wait, there’s more?)
  • 41. Custom Auto-configuration “Sometimes, magic is just someone spending more time on something than anyone else might reasonably expect.” ― Teller
  • 42. Auto-Configuration  Best known Spring Boot feature  Condition configuration classes, evaluated at startup  After your own config classes  Can be great for custom libraries as well  Micro-services  Inter-project
  • 43. Write Your Own Auto-Configuration  Create a Java library  Add one or more @Configuration classes  List them in a META-INF/spring.factories file  Under key org.springframework.boot.autoconfigure. EnableAutoConfiguration
  • 44. Examples  Logging  MDC setup, Sleuth overrides  Metrics  Shared custom tags, cardinality reduction filters, exposing trace IDs in responses, accepting external trace IDs  HTTP Client  Custom HTTP client setup, RestTemplate setup  MVC  Custom ErrorAttributes, shared ControllerAdvice
  • 45. Caveats  Consider interaction with Boot’s auto-config  Use @AutoConfigureBefore/-After where needed  Allow overrides and disabling selectively