SlideShare una empresa de Scribd logo
1 de 45
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
Amazon Web Services
 
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
Amazon Web Services
 
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
Amazon 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 microservice
Amazon Web Services
 

La actualidad más candente (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
 

Similar a 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
 
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
Andy Peterson
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 

Similar a 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
 

Más de Joris Kuipers

Más 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
 

Último

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Último (20)

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 

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