SlideShare a Scribd company logo
1 of 55
Download to read offline
SPRING BOOT
A PRESENTATION AFTER „SPRING BOOT IN ACTION” EBOOK
SPRING FRAMEWORK
Advantages:
•A lightweight alternative to J2EE
•POJO+DI+AOP instead of EJB (light component code)
•annotation-based component-scanning reduced use of XML configuration (Spring 2.5)
•Java-based configuration as a type-safe and refactorable option to XML (Spring 3.0)
SPRING FRAMEWORK
Problems:
•Certain features like transaction management and Spring MVC still require explicit
configuration
•Enabling third-party library features such asThymeleaf-based web views require explicit
configuration
•Configuring servlets and filters (such as Spring’s DispatcherServlet) required explicit
configuration in web.xml or in a servlet initializer
•project dependency management hell (library versions etc)
SPRING BOOT
Provides:
•Automatic configuration for common web app functionalities (JPA, security, Spring MVC etc)
•Starter dependencies (select tehnology stack and libraries are selected automatically)
•The command-line interface (write just app code , no traditional project build needed)
•The Actuator (dashboard to inspect inside running app) (HTTP request trace, conf.
properties, resource metrics, threads state)
•What Spring Boot isn’t : no app server, it embeds a servlet container, does not generate
code
SPRING BOOT CLI
• an easy way to get started with Spring Boot and to prototype simple applications
• leverages starter dependencies and auto-configuration to let you focus on writing code
SPRING BOOT CLI – HELLO WORD
CLI cmd line:
spring run HelloController.groovy
http://localhost:8080/
HelloController.groovy
SPRING INITIALIZR
• a web application that can generate a Spring Boot project structure for you
Spring Initializr can be used in several ways:
• Through a web-based interface (http://start.spring.io)
• Via SpringTool Suite (Spring Boot IDE based on Eclipse)
• Via IntelliJ IDEA
• Using the Spring Boot CLI:
• spring init -dweb,jpa,security --build gradle -p jar –x
• list parameter: spring init -l
FIRST SPRING BOOT APPLICATION
• we’re going to use Spring MVC to handle web requests
• Thymeleaf to define web views
• Spring Data JPA to persist the reading selections to a database. For now, that database
will be an embedded H2 database.
• we’ll write the application code in Java for now. (also Groovy is an option)
• we’ll use Gradle as our build tool of choice.
• spring init -dweb,data-jpa,h2,thymeleaf --build gradle readinglist
FIRST SPRING BOOT APPLICATION
• ReadingListApplication class serves two purposes in a Spring Boot application:
• configuration and bootstrapping (has a main() method to run it directly)
• annotated with @SpringBootApplication (@Configuration + @ComponentScan
+@EnableAutoConfiguration)
• @Configuration - Designates a class as a configuration class using Spring’s Java-based configuration
• @ComponentScan - Enables component-scanning so that the web controller classes and other
components you write will be automatically discovered and registered as beans in the Spring application
context
• gradle bootRun (build and run it)
TESTING SPRING BOOT APPLICATIONS
• ReadingListApplicationTests annotated with:
• @RunWith(SpringJUnit4ClassRunner.class)
• @SpringApplicationConfiguration(classes = ReadingListApplication.class) (Load
context via Spring Boot)
• @WebAppConfiguration
USING STARTER DEPENDENCIES
• compile("org.springframework:spring-web:4.1.6.RELEASE")
• compile("org.thymeleaf:thymeleaf-spring4:2.1.4.RELEASE")
• compile("org.springframework.data:spring-data-jpa:1.8.0.RELEASE")
• compile("org.hibernate:hibernate-entitymanager:jar:4.3.8.Final")
• compile("com.h2database:h2:1.4.187")
CUSTOMIZING STARTER DEPENDENCIES
• If you’re using Gradle, you can exclude transitive dependencies like this:
compile("org.springframework.boot:spring-boot-starter-web") {
exclude group: 'com.fasterxml.jackson.core‘
}
Then specify newer version:
compile("com.fasterxml.jackson.core:jackson-databind:2.4.3")
USING AUTOMATIC CONFIGURATION
• There are nearly 200 such decisions that Spring Boot makes with regard to autoconfiguration
every time an application starts up, covering such areas as: security, integration,
persistence, and web development. Examples:
• Is Spring’s JdbcTemplate available on the classpath? If so and if there is a Data-Source bean,
then auto-configure a JdbcTemplate bean.
• Is Thymeleaf on the classpath? If so, then configure aThymeleaf template resolver, view
resolver, and template engine.
• Is Spring Security on the classpath? If so, then configure a very basic web security setup.
• in your application only business code is needed, no boiler plate configuration
SPRING 4.0. CONDITIONAL CONFIGURATION
• Spring Boot auto-configuration is built internally upon Spring 4 conditional configuration
• allows for configuration to be available in an application, but to be ignored unless certain conditions are
met
• implement the Condition interface and override its matches() method the use it in annotation
@Conditional(JdbcTemplateCondition.class to specify when a bean should be created
• @ConditionalOnBean …the specified bean has been configured
• @ConditionalOnMissingBean …the specified bean has not already been configured
• @ConditionalOnClass …the specified class is available on the classpath
• @ConditionalOnMissingClass …the specified class is not available on the classpath
AUTO-CONFIGURATION DECISIONS
• to configure a
JdbcTemplate bean only if needed
• H2 is on the classpath -> H2 db is created
• Spring Data JPA is on the classpath -> automatically create repository implementations from repository
interfaces.
• Tomcat is on the classpath (transitively referred to by the web starter
dependency) -> an embedded Tomcat container will be started to listen on port 8080
CUSTOMIZING CONFIGURATION
• Overriding auto-configured beans
• Configuring with external properties
• Customizing error pages
OVERRIDING SPRING AUTO-CONFIGURED BEANS
- all you need to do to override Spring Boot auto-configuration is to write
explicit configuration. Spring Boot will see your configuration, step back, and let your
configuration take precedence.
CONFIGURING WITH EXTERNAL PROPERTIES
• specify the property as a command-line parameter:
$ java -jar readinglist-0.0.1-SNAPSHOT.jar --spring.main.show-banner=false
• create a file named application.properties which contains
spring.main.show-banner=false
• create aYAML file named application.yml which contains:
CONFIGURING WITH EXTERNAL PROPERTIES
Spring Boot will draw properties from several property sources, including the following:
•Command-line arguments / Operating system environment variables
•JNDI attributes from java:comp/env, or JVM system properties
•Randomly generated values for properties prefixed with random.* (referenced when setting other
properties, such as `${random.long})
•An application.properties or application.yml file outside of the application or packaged inside of the
Application
•Property sources specified by @PropertySource
•Default properties
CONFIGURING WITH EXTERNAL PROPERTIES
As for the application.properties and application.yml files, they can reside in any of four
locations:
•Externally, in a /config subdirectory of the directory from which the application is run
•Externally, in the directory from which the application is run
•Internally, in a package named “config”
•Internally, at the root of the classpath
FINE-TUNING AUTO-CONFIGURATION
• Disabling thymeleaf cache: spring.thymeleaf.cache=false
• Configuring the embedded server: server.port=8000
• Swapping out Logback for another logging implementation:
FINE-TUNING AUTO-CONFIGURATION
Switch datasource from H2 to MySQL:
Confgure logging:
EXTERNALLY CONFIGURING APPLICATION BEANS
amazon.associateId=habuma-20
Or keep all properties in a dedicated bean:
CONFIGURING WITH PROFILES
• PROFILE-SPECIFIC PROPERTIES FILES :“application-{profile}.properties”
• MULTI-PROFILEYAML FILES (you also have the option of expressing configuration
properties for all profiles in a single application.yml file)
• Customize security configuration only for production:
spring.profiles.active=production
TESTING WITH SPRING BOOT
• Integration testing
• Testing apps in a server
• Spring Boot’s test utilities
AUTO-CONFIGURATION FOR INTEGRATION
TESTING WITH SPRING
@RunWith is given
SpringJUnit4ClassRunner.class to enable Spring
integration testing, allows autowiring
@ContextConfiguration - load the Spring
application context given
the specification defined in
AddressBookConfiguration
AUTO-CONFIGURATION FOR INTEGRATION
TESTING WITH SPRING BOOT
@SpringApplicationConfiguration
replaces @ContextConfiguration
when writing tests for Spring Boot
applications
- unlike @ContextConfiguration, @SpringApplicationConfiguration
loads the Spring application context using SpringApplication the same way
and with the same treatment it would get if it was being loaded in a production application.
This includes the loading of external properties and Spring Boot logging.
TESTING WEB APPLICATIONS
To properly test a web application, you need a way to throw actual HTTP requests at
it and assert that it processes those requests correctly. Fortunately, there are two options
available to Spring Boot application developers that make those kinds of tests possible:
•Spring Mock MVC—Enables controllers to be tested in a mocked approximation
of a servlet container without actually starting an application server
•Web integration tests—Actually starts the application in an embedded servlet container
(such as Tomcat or Jetty), enabling tests that exercise the application in a
real application server
MOCKING SPRING MVC
MOCKING SPRING MVC
@WebAppConfiguration - declares that the application context created by SpringJUnit4ClassRunner
should be a WebApplicationContext (as opposed to a basic non-web ApplicationContext).
The setupMockMvc() method is annotated with JUnit’s @Before, indicating that it
should be executed before any test methods. It passes the injected WebApplication-
Context into the webAppContextSetup() method and then calls build() to produce a
MockMvc instance, which is assigned to an instance variable for test methods to use.
TESTING WEB SECURITY
testCompile("org.springframework.security:spring-security-test")
Spring Security offers two annotations for authenticated request:
•@WithMockUser—Loads the security context with a UserDetails using the given
username, password, and authorization
•@WithUserDetails—Loads the security context by looking up a UserDetails
object for the given username
TESTING WEB SECURITY
TESTING WEB SECURITY
TESTING A RUNNING APPLICATION
• @WebIntegrationTest - Spring Boot will not only create an application context for your
test, but also to start an embedded servlet container.
TESTING HTML PAGES WITH SELENIUM
• RestTemplate is fine for simple requests and it’s perfect for testing REST endpoints
testCompile("org.seleniumhq.selenium:selenium-java:2.45.0")
TESTING HTML PAGES WITH SELENIUM
TESTING HTML PAGES WITH SELENIUM
TESTING HTML PAGES WITH SELENIUM
TAKING A PEEK INSIDE WITH THE ACTUATOR
• Actuator web endpoints
To enable as REST service: compile 'org.springframework.boot:spring-boot-starter-actuator‘
• Adjusting the Actuator
• Shelling into a running application
As remote shell in app: compile("org.springframework.boot:spring-boot-starter-remote-shell")
• Securing the Actuator
EXPLORING THE ACTUATOR’S ENDPOINTS
EXPLORING THE ACTUATOR’S ENDPOINTS
CUSTOMIZING THE ACTUATOR
As it turns out, the Actuator can be customized in several ways, including the following:
•Renaming endpoints
•Enabling and disabling endpoints
•Defining custom metrics and gauges
•Creating a custom repository for storing trace data
•Plugging in custom health indicators
DEPLOYING SPRING BOOT APPLICATIONS
• DeployingWAR files
• Database migration
• Deploying to the cloud
DEPLOYINGTO AN APPLICATION SERVER
Building a WAR file:
Instead of web.xml file or servlet initializer use this
in order to configure Spring’s DispatcherServlet and register any beans of type Filter, Servlet:
DEPLOYING ON TOMCAT
• $ gradle build -> will produce a file named readinglist-0.0.1-SNAPSHOT.war in build/libs
• copy the WAR file intoTomcat’s webapps directory
• http://server:_port_/readinglist-0.0.1-SNAPSHOT
• $ java -jar readinglist-0.0.1-SNAPSHOT.war (also possible because we have main())
SWITCH DATESOURCE TO A PRODUCTION DB
• Replace the auto-configured DataSource bean for H2 db with Postgress db
• org.apache.tomcat.jdbc.pool.DataSource:
...OR CONFIGURE PRODUCTION PROFILE
...and activate PRODUCTION PROFILE:
$ export SPRING_PROFILES_ACTIVE=production
CONFIGURE SCHEMA CREATION
This configuration is default for H2 but we need to explicit set it for Postgres: the schema should be
created when Hibernate’s SessionFactory is created and dropped when it is closed
... or for production Spring Boot includes auto-configuration support for
two popular database migration libraries:
•Flyway (http://flywaydb.org)
•Liquibase (www.liquibase.org)
DEFINING DATABASE MIGRATION WITH FLYWAY
• compile("org.flywaydb:flyway-core")
• Set spring.jpa.hibernate.ddl-auto to none.
• Put in main/resources/db/migration SQL schema creation script with this signature:
Flyway Disadvantage:
- with SQL, you run the risk of defining a migration script that
works with
one database platform but not another
DEFINING DATABASE MIGRATION WITH LIQUIBASE
• compile("org.liquibase:liquibase-core")
• Set property for liquibase change-log to xml / yaml / json / SQL
• Liquibase changesets are all collected in the same file (unlike Flyway)
DEPLOYING TO CLOUD FOUNDRY
• Cloud Foundry is a PaaS (platform as a service) platform from Pivotal, the same company
that sponsors the Spring Framework
• it is both open source and has several commercial distributions
• We deploy on PWS : http://run.pivotal.io (60-day free trial)
• download and install the cf command-line tool from https://console.run.pivotal.io/tools
• Login : $ cf login -a https://api.run.pivotal.io
• $ cf push sbia-readinglist -p build/libs/readinglist.war (first param = app subdomain)
DEPLOYING TO CLOUD FOUNDRY
• full URL for the application will be http://sbia-readinglist.cfapps.io
To generate unique subdomain (add 2 random woirds):
• cf push sbia-readinglist -p build/libs/readinglist.war --random-route
• The resulting subdomain: sbia-readinglist-gastroenterological-stethoscope
• Data does not survive app restart because we using H2 (login, use app URL, use
command : cf restart) (check db by requesting the Actuator’s /health endpoint)
DEPLOY POSTGRESQL IN CLOUD FOUNDRY
• List available plans:
$ cf marketplace -s elephantsql
• Create postgres db service with the free “turtle” plan:
$ cf create-service elephantsql turtle readinglistdb
• Bind service to our app:
$ cf bind-service sbia-readinglist readinglistdb
• Replace Datasource & Redeploy app:
$ cf restage sbia-readinglist
SPRING BOOT DEVELOPER TOOLS
Spring Boot 1.3 introduced a new set of developer tools that make it even easier to
work with Spring Boot at development time. Among its many capabilities are
•Automatic restart—Restarts a running application when files are changed in the classpath
•LiveReload support—Changes to resources trigger a browser refresh automatically
•Remote development—Supports automatic restart and LiveReload when deployed remotely
•Development property defaults—Provides sensible development defaults for some configuration
properties
•To enable it, use: compile "org.springframework.boot:spring-boot-devtools"
THE END

More Related Content

What's hot (20)

Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring framework core
Spring framework coreSpring framework core
Spring framework core
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Xke spring boot
Xke spring bootXke spring boot
Xke spring boot
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring framework
Spring frameworkSpring framework
Spring framework
 

Similar to Spring Boot in Action

Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservicesNilanjan Roy
 
Spring essentials 1 (Spring Series 01)
Spring essentials 1 (Spring Series 01)Spring essentials 1 (Spring Series 01)
Spring essentials 1 (Spring Series 01)Heartin Jacob
 
"Spring Boot. Boot up your development" Сергей Моренец
"Spring Boot. Boot up your development" Сергей Моренец"Spring Boot. Boot up your development" Сергей Моренец
"Spring Boot. Boot up your development" Сергей МоренецFwdays
 
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
 
Spring Boot. Boot up your development
Spring Boot. Boot up your developmentSpring Boot. Boot up your development
Spring Boot. Boot up your developmentStrannik_2013
 
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 MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC frameworkMohit Gupta
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to SpringSujit Kumar
 
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»DataArt
 
Building a Spring Boot Application - Ask the Audience! (from JavaLand 2017)
Building a Spring Boot Application - Ask the Audience!  (from JavaLand 2017)Building a Spring Boot Application - Ask the Audience!  (from JavaLand 2017)
Building a Spring Boot Application - Ask the Audience! (from JavaLand 2017)🎤 Hanno Embregts 🎸
 
Lightning web components
Lightning web components Lightning web components
Lightning web components Cloud Analogy
 
Java spring framework
Java spring frameworkJava spring framework
Java spring frameworkRajiv Gupta
 
AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)Igor Talevski
 
Building a Spring Boot Application - Ask the Audience! (from JVMCon 2018)
Building a Spring Boot Application - Ask the Audience! (from JVMCon 2018)Building a Spring Boot Application - Ask the Audience! (from JVMCon 2018)
Building a Spring Boot Application - Ask the Audience! (from JVMCon 2018)🎤 Hanno Embregts 🎸
 
Spring Boot & Actuators
Spring Boot & ActuatorsSpring Boot & Actuators
Spring Boot & ActuatorsVMware Tanzu
 
Building a Spring Boot Application - Ask the Audience!
Building a Spring Boot Application - Ask the Audience!Building a Spring Boot Application - Ask the Audience!
Building a Spring Boot Application - Ask the Audience!🎤 Hanno Embregts 🎸
 

Similar to Spring Boot in Action (20)

Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservices
 
Story ofcorespring infodeck
Story ofcorespring infodeckStory ofcorespring infodeck
Story ofcorespring infodeck
 
Spring essentials 1 (Spring Series 01)
Spring essentials 1 (Spring Series 01)Spring essentials 1 (Spring Series 01)
Spring essentials 1 (Spring Series 01)
 
"Spring Boot. Boot up your development" Сергей Моренец
"Spring Boot. Boot up your development" Сергей Моренец"Spring Boot. Boot up your development" Сергей Моренец
"Spring Boot. Boot up your development" Сергей Моренец
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
Spring Boot. Boot up your development
Spring Boot. Boot up your developmentSpring Boot. Boot up your development
Spring Boot. Boot up your development
 
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 MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to Spring
 
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
Станислав Сидоренко «DeviceHive Java Server – миграция на Spring Boot»
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Building a Spring Boot Application - Ask the Audience! (from JavaLand 2017)
Building a Spring Boot Application - Ask the Audience!  (from JavaLand 2017)Building a Spring Boot Application - Ask the Audience!  (from JavaLand 2017)
Building a Spring Boot Application - Ask the Audience! (from JavaLand 2017)
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Lightning web components
Lightning web components Lightning web components
Lightning web components
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
 
AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)AngularJS 1.x - your first application (problems and solutions)
AngularJS 1.x - your first application (problems and solutions)
 
Building a Spring Boot Application - Ask the Audience! (from JVMCon 2018)
Building a Spring Boot Application - Ask the Audience! (from JVMCon 2018)Building a Spring Boot Application - Ask the Audience! (from JVMCon 2018)
Building a Spring Boot Application - Ask the Audience! (from JVMCon 2018)
 
Spring Boot & Actuators
Spring Boot & ActuatorsSpring Boot & Actuators
Spring Boot & Actuators
 
Building a Spring Boot Application - Ask the Audience!
Building a Spring Boot Application - Ask the Audience!Building a Spring Boot Application - Ask the Audience!
Building a Spring Boot Application - Ask the Audience!
 

Recently uploaded

Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLBig Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLAlluxio, Inc.
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadIvo Andreev
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionsNirav Modi
 
Enterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze IncEnterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze Incrobinwilliams8624
 
online pdf editor software solutions.pdf
online pdf editor software solutions.pdfonline pdf editor software solutions.pdf
online pdf editor software solutions.pdfMeon Technology
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeNeo4j
 
Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxJoão Esperancinha
 
Generative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilGenerative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilVICTOR MAESTRE RAMIREZ
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Jaydeep Chhasatia
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxAutus Cyber Tech
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024Mind IT Systems
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageDista
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesSoftwareMill
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesShyamsundar Das
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfTobias Schneck
 
Streamlining Your Application Builds with Cloud Native Buildpacks
Streamlining Your Application Builds  with Cloud Native BuildpacksStreamlining Your Application Builds  with Cloud Native Buildpacks
Streamlining Your Application Builds with Cloud Native BuildpacksVish Abrams
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIIvo Andreev
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsJaydeep Chhasatia
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...OnePlan Solutions
 

Recently uploaded (20)

Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/MLBig Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
Big Data Bellevue Meetup | Enhancing Python Data Loading in the Cloud for AI/ML
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and Bad
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspections
 
Enterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze IncEnterprise Document Management System - Qualityze Inc
Enterprise Document Management System - Qualityze Inc
 
online pdf editor software solutions.pdf
online pdf editor software solutions.pdfonline pdf editor software solutions.pdf
online pdf editor software solutions.pdf
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG time
 
Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptx
 
Generative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-CouncilGenerative AI for Cybersecurity - EC-Council
Generative AI for Cybersecurity - EC-Council
 
Salesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptxSalesforce AI Associate Certification.pptx
Salesforce AI Associate Certification.pptx
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptx
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
 
Growing Oxen: channel operators and retries
Growing Oxen: channel operators and retriesGrowing Oxen: channel operators and retries
Growing Oxen: channel operators and retries
 
Watermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security ChallengesWatermarking in Source Code: Applications and Security Challenges
Watermarking in Source Code: Applications and Security Challenges
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
 
Streamlining Your Application Builds with Cloud Native Buildpacks
Streamlining Your Application Builds  with Cloud Native BuildpacksStreamlining Your Application Builds  with Cloud Native Buildpacks
Streamlining Your Application Builds with Cloud Native Buildpacks
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AI
 
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
 

Spring Boot in Action

  • 1. SPRING BOOT A PRESENTATION AFTER „SPRING BOOT IN ACTION” EBOOK
  • 2. SPRING FRAMEWORK Advantages: •A lightweight alternative to J2EE •POJO+DI+AOP instead of EJB (light component code) •annotation-based component-scanning reduced use of XML configuration (Spring 2.5) •Java-based configuration as a type-safe and refactorable option to XML (Spring 3.0)
  • 3. SPRING FRAMEWORK Problems: •Certain features like transaction management and Spring MVC still require explicit configuration •Enabling third-party library features such asThymeleaf-based web views require explicit configuration •Configuring servlets and filters (such as Spring’s DispatcherServlet) required explicit configuration in web.xml or in a servlet initializer •project dependency management hell (library versions etc)
  • 4. SPRING BOOT Provides: •Automatic configuration for common web app functionalities (JPA, security, Spring MVC etc) •Starter dependencies (select tehnology stack and libraries are selected automatically) •The command-line interface (write just app code , no traditional project build needed) •The Actuator (dashboard to inspect inside running app) (HTTP request trace, conf. properties, resource metrics, threads state) •What Spring Boot isn’t : no app server, it embeds a servlet container, does not generate code
  • 5. SPRING BOOT CLI • an easy way to get started with Spring Boot and to prototype simple applications • leverages starter dependencies and auto-configuration to let you focus on writing code
  • 6. SPRING BOOT CLI – HELLO WORD CLI cmd line: spring run HelloController.groovy http://localhost:8080/ HelloController.groovy
  • 7. SPRING INITIALIZR • a web application that can generate a Spring Boot project structure for you Spring Initializr can be used in several ways: • Through a web-based interface (http://start.spring.io) • Via SpringTool Suite (Spring Boot IDE based on Eclipse) • Via IntelliJ IDEA • Using the Spring Boot CLI: • spring init -dweb,jpa,security --build gradle -p jar –x • list parameter: spring init -l
  • 8. FIRST SPRING BOOT APPLICATION • we’re going to use Spring MVC to handle web requests • Thymeleaf to define web views • Spring Data JPA to persist the reading selections to a database. For now, that database will be an embedded H2 database. • we’ll write the application code in Java for now. (also Groovy is an option) • we’ll use Gradle as our build tool of choice. • spring init -dweb,data-jpa,h2,thymeleaf --build gradle readinglist
  • 9. FIRST SPRING BOOT APPLICATION • ReadingListApplication class serves two purposes in a Spring Boot application: • configuration and bootstrapping (has a main() method to run it directly) • annotated with @SpringBootApplication (@Configuration + @ComponentScan +@EnableAutoConfiguration) • @Configuration - Designates a class as a configuration class using Spring’s Java-based configuration • @ComponentScan - Enables component-scanning so that the web controller classes and other components you write will be automatically discovered and registered as beans in the Spring application context • gradle bootRun (build and run it)
  • 10. TESTING SPRING BOOT APPLICATIONS • ReadingListApplicationTests annotated with: • @RunWith(SpringJUnit4ClassRunner.class) • @SpringApplicationConfiguration(classes = ReadingListApplication.class) (Load context via Spring Boot) • @WebAppConfiguration
  • 11. USING STARTER DEPENDENCIES • compile("org.springframework:spring-web:4.1.6.RELEASE") • compile("org.thymeleaf:thymeleaf-spring4:2.1.4.RELEASE") • compile("org.springframework.data:spring-data-jpa:1.8.0.RELEASE") • compile("org.hibernate:hibernate-entitymanager:jar:4.3.8.Final") • compile("com.h2database:h2:1.4.187")
  • 12. CUSTOMIZING STARTER DEPENDENCIES • If you’re using Gradle, you can exclude transitive dependencies like this: compile("org.springframework.boot:spring-boot-starter-web") { exclude group: 'com.fasterxml.jackson.core‘ } Then specify newer version: compile("com.fasterxml.jackson.core:jackson-databind:2.4.3")
  • 13. USING AUTOMATIC CONFIGURATION • There are nearly 200 such decisions that Spring Boot makes with regard to autoconfiguration every time an application starts up, covering such areas as: security, integration, persistence, and web development. Examples: • Is Spring’s JdbcTemplate available on the classpath? If so and if there is a Data-Source bean, then auto-configure a JdbcTemplate bean. • Is Thymeleaf on the classpath? If so, then configure aThymeleaf template resolver, view resolver, and template engine. • Is Spring Security on the classpath? If so, then configure a very basic web security setup. • in your application only business code is needed, no boiler plate configuration
  • 14. SPRING 4.0. CONDITIONAL CONFIGURATION • Spring Boot auto-configuration is built internally upon Spring 4 conditional configuration • allows for configuration to be available in an application, but to be ignored unless certain conditions are met • implement the Condition interface and override its matches() method the use it in annotation @Conditional(JdbcTemplateCondition.class to specify when a bean should be created • @ConditionalOnBean …the specified bean has been configured • @ConditionalOnMissingBean …the specified bean has not already been configured • @ConditionalOnClass …the specified class is available on the classpath • @ConditionalOnMissingClass …the specified class is not available on the classpath
  • 15. AUTO-CONFIGURATION DECISIONS • to configure a JdbcTemplate bean only if needed • H2 is on the classpath -> H2 db is created • Spring Data JPA is on the classpath -> automatically create repository implementations from repository interfaces. • Tomcat is on the classpath (transitively referred to by the web starter dependency) -> an embedded Tomcat container will be started to listen on port 8080
  • 16. CUSTOMIZING CONFIGURATION • Overriding auto-configured beans • Configuring with external properties • Customizing error pages
  • 17. OVERRIDING SPRING AUTO-CONFIGURED BEANS - all you need to do to override Spring Boot auto-configuration is to write explicit configuration. Spring Boot will see your configuration, step back, and let your configuration take precedence.
  • 18. CONFIGURING WITH EXTERNAL PROPERTIES • specify the property as a command-line parameter: $ java -jar readinglist-0.0.1-SNAPSHOT.jar --spring.main.show-banner=false • create a file named application.properties which contains spring.main.show-banner=false • create aYAML file named application.yml which contains:
  • 19. CONFIGURING WITH EXTERNAL PROPERTIES Spring Boot will draw properties from several property sources, including the following: •Command-line arguments / Operating system environment variables •JNDI attributes from java:comp/env, or JVM system properties •Randomly generated values for properties prefixed with random.* (referenced when setting other properties, such as `${random.long}) •An application.properties or application.yml file outside of the application or packaged inside of the Application •Property sources specified by @PropertySource •Default properties
  • 20. CONFIGURING WITH EXTERNAL PROPERTIES As for the application.properties and application.yml files, they can reside in any of four locations: •Externally, in a /config subdirectory of the directory from which the application is run •Externally, in the directory from which the application is run •Internally, in a package named “config” •Internally, at the root of the classpath
  • 21. FINE-TUNING AUTO-CONFIGURATION • Disabling thymeleaf cache: spring.thymeleaf.cache=false • Configuring the embedded server: server.port=8000 • Swapping out Logback for another logging implementation:
  • 22. FINE-TUNING AUTO-CONFIGURATION Switch datasource from H2 to MySQL: Confgure logging:
  • 23. EXTERNALLY CONFIGURING APPLICATION BEANS amazon.associateId=habuma-20 Or keep all properties in a dedicated bean:
  • 24. CONFIGURING WITH PROFILES • PROFILE-SPECIFIC PROPERTIES FILES :“application-{profile}.properties” • MULTI-PROFILEYAML FILES (you also have the option of expressing configuration properties for all profiles in a single application.yml file) • Customize security configuration only for production: spring.profiles.active=production
  • 25. TESTING WITH SPRING BOOT • Integration testing • Testing apps in a server • Spring Boot’s test utilities
  • 26. AUTO-CONFIGURATION FOR INTEGRATION TESTING WITH SPRING @RunWith is given SpringJUnit4ClassRunner.class to enable Spring integration testing, allows autowiring @ContextConfiguration - load the Spring application context given the specification defined in AddressBookConfiguration
  • 27. AUTO-CONFIGURATION FOR INTEGRATION TESTING WITH SPRING BOOT @SpringApplicationConfiguration replaces @ContextConfiguration when writing tests for Spring Boot applications - unlike @ContextConfiguration, @SpringApplicationConfiguration loads the Spring application context using SpringApplication the same way and with the same treatment it would get if it was being loaded in a production application. This includes the loading of external properties and Spring Boot logging.
  • 28. TESTING WEB APPLICATIONS To properly test a web application, you need a way to throw actual HTTP requests at it and assert that it processes those requests correctly. Fortunately, there are two options available to Spring Boot application developers that make those kinds of tests possible: •Spring Mock MVC—Enables controllers to be tested in a mocked approximation of a servlet container without actually starting an application server •Web integration tests—Actually starts the application in an embedded servlet container (such as Tomcat or Jetty), enabling tests that exercise the application in a real application server
  • 30. MOCKING SPRING MVC @WebAppConfiguration - declares that the application context created by SpringJUnit4ClassRunner should be a WebApplicationContext (as opposed to a basic non-web ApplicationContext). The setupMockMvc() method is annotated with JUnit’s @Before, indicating that it should be executed before any test methods. It passes the injected WebApplication- Context into the webAppContextSetup() method and then calls build() to produce a MockMvc instance, which is assigned to an instance variable for test methods to use.
  • 31. TESTING WEB SECURITY testCompile("org.springframework.security:spring-security-test") Spring Security offers two annotations for authenticated request: •@WithMockUser—Loads the security context with a UserDetails using the given username, password, and authorization •@WithUserDetails—Loads the security context by looking up a UserDetails object for the given username
  • 34. TESTING A RUNNING APPLICATION • @WebIntegrationTest - Spring Boot will not only create an application context for your test, but also to start an embedded servlet container.
  • 35. TESTING HTML PAGES WITH SELENIUM • RestTemplate is fine for simple requests and it’s perfect for testing REST endpoints testCompile("org.seleniumhq.selenium:selenium-java:2.45.0")
  • 36. TESTING HTML PAGES WITH SELENIUM
  • 37. TESTING HTML PAGES WITH SELENIUM
  • 38. TESTING HTML PAGES WITH SELENIUM
  • 39. TAKING A PEEK INSIDE WITH THE ACTUATOR • Actuator web endpoints To enable as REST service: compile 'org.springframework.boot:spring-boot-starter-actuator‘ • Adjusting the Actuator • Shelling into a running application As remote shell in app: compile("org.springframework.boot:spring-boot-starter-remote-shell") • Securing the Actuator
  • 42. CUSTOMIZING THE ACTUATOR As it turns out, the Actuator can be customized in several ways, including the following: •Renaming endpoints •Enabling and disabling endpoints •Defining custom metrics and gauges •Creating a custom repository for storing trace data •Plugging in custom health indicators
  • 43. DEPLOYING SPRING BOOT APPLICATIONS • DeployingWAR files • Database migration • Deploying to the cloud
  • 44. DEPLOYINGTO AN APPLICATION SERVER Building a WAR file: Instead of web.xml file or servlet initializer use this in order to configure Spring’s DispatcherServlet and register any beans of type Filter, Servlet:
  • 45. DEPLOYING ON TOMCAT • $ gradle build -> will produce a file named readinglist-0.0.1-SNAPSHOT.war in build/libs • copy the WAR file intoTomcat’s webapps directory • http://server:_port_/readinglist-0.0.1-SNAPSHOT • $ java -jar readinglist-0.0.1-SNAPSHOT.war (also possible because we have main())
  • 46. SWITCH DATESOURCE TO A PRODUCTION DB • Replace the auto-configured DataSource bean for H2 db with Postgress db • org.apache.tomcat.jdbc.pool.DataSource:
  • 47. ...OR CONFIGURE PRODUCTION PROFILE ...and activate PRODUCTION PROFILE: $ export SPRING_PROFILES_ACTIVE=production
  • 48. CONFIGURE SCHEMA CREATION This configuration is default for H2 but we need to explicit set it for Postgres: the schema should be created when Hibernate’s SessionFactory is created and dropped when it is closed ... or for production Spring Boot includes auto-configuration support for two popular database migration libraries: •Flyway (http://flywaydb.org) •Liquibase (www.liquibase.org)
  • 49. DEFINING DATABASE MIGRATION WITH FLYWAY • compile("org.flywaydb:flyway-core") • Set spring.jpa.hibernate.ddl-auto to none. • Put in main/resources/db/migration SQL schema creation script with this signature: Flyway Disadvantage: - with SQL, you run the risk of defining a migration script that works with one database platform but not another
  • 50. DEFINING DATABASE MIGRATION WITH LIQUIBASE • compile("org.liquibase:liquibase-core") • Set property for liquibase change-log to xml / yaml / json / SQL • Liquibase changesets are all collected in the same file (unlike Flyway)
  • 51. DEPLOYING TO CLOUD FOUNDRY • Cloud Foundry is a PaaS (platform as a service) platform from Pivotal, the same company that sponsors the Spring Framework • it is both open source and has several commercial distributions • We deploy on PWS : http://run.pivotal.io (60-day free trial) • download and install the cf command-line tool from https://console.run.pivotal.io/tools • Login : $ cf login -a https://api.run.pivotal.io • $ cf push sbia-readinglist -p build/libs/readinglist.war (first param = app subdomain)
  • 52. DEPLOYING TO CLOUD FOUNDRY • full URL for the application will be http://sbia-readinglist.cfapps.io To generate unique subdomain (add 2 random woirds): • cf push sbia-readinglist -p build/libs/readinglist.war --random-route • The resulting subdomain: sbia-readinglist-gastroenterological-stethoscope • Data does not survive app restart because we using H2 (login, use app URL, use command : cf restart) (check db by requesting the Actuator’s /health endpoint)
  • 53. DEPLOY POSTGRESQL IN CLOUD FOUNDRY • List available plans: $ cf marketplace -s elephantsql • Create postgres db service with the free “turtle” plan: $ cf create-service elephantsql turtle readinglistdb • Bind service to our app: $ cf bind-service sbia-readinglist readinglistdb • Replace Datasource & Redeploy app: $ cf restage sbia-readinglist
  • 54. SPRING BOOT DEVELOPER TOOLS Spring Boot 1.3 introduced a new set of developer tools that make it even easier to work with Spring Boot at development time. Among its many capabilities are •Automatic restart—Restarts a running application when files are changed in the classpath •LiveReload support—Changes to resources trigger a browser refresh automatically •Remote development—Supports automatic restart and LiveReload when deployed remotely •Development property defaults—Provides sensible development defaults for some configuration properties •To enable it, use: compile "org.springframework.boot:spring-boot-devtools"