SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
Jonathan Holloway
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
Rajiv Srivastava
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
Spring Boot & Actuators
Spring Boot & ActuatorsSpring Boot & Actuators
Spring Boot & Actuators
VMware Tanzu
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Spring boot
Spring bootSpring boot
Spring boot
Gyanendra Yadav
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jiayun Zhou
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Serhat Can
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
Mehul Jariwala
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
NexThoughts Technologies
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Pei-Tang Huang
 
Spring boot
Spring bootSpring boot
Spring boot
sdeeg
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
Rasheed Waraich
 
Spring Core
Spring CoreSpring Core
Spring Core
Pushan Bhattacharya
 
Spring boot
Spring bootSpring boot
Spring boot
Pradeep Shanmugam
 
Spring boot
Spring bootSpring boot
Spring boot
Bhagwat Kumar
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
Josué Neis
 
Spring Boot
Spring BootSpring Boot
Spring Boot
HongSeong Jeon
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
zeeshanhanif
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
Hamid Ghorbani
 

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
Nilanjan Roy
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applications
michaelaaron25322
 
Xke spring boot
Xke spring bootXke spring boot
Xke spring boot
sourabh aggarwal
 
Story ofcorespring infodeck
Story ofcorespring infodeckStory ofcorespring infodeck
Story ofcorespring infodeck
Makarand Bhatambarekar
 
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 - a framework written by developers
Spring - a framework written by developersSpring - a framework written by developers
Spring - a framework written by developers
MarcioSoaresPereira1
 
"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
Spring BootSpring Boot
Spring Boot
Jaran Flaath
 
Spring Boot. Boot up your development
Spring Boot. Boot up your developmentSpring Boot. Boot up your development
Spring Boot. Boot up your development
Strannik_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).pdf
Appster1
 
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
Appster1
 
Spring Boot Interview Questions PDF By ScholarHat
Spring Boot Interview Questions PDF By ScholarHatSpring Boot Interview Questions PDF By ScholarHat
Spring Boot Interview Questions PDF By ScholarHat
Scholarhat
 
Springboot - A milestone framework in Java Development
Springboot - A milestone framework in Java DevelopmentSpringboot - A milestone framework in Java Development
Springboot - A milestone framework in Java Development
Expeed Software
 
cadec-2029-SPRING SPRING BOOT LEARNIGN PURPOSE
cadec-2029-SPRING SPRING BOOT LEARNIGN PURPOSEcadec-2029-SPRING SPRING BOOT LEARNIGN PURPOSE
cadec-2029-SPRING SPRING BOOT LEARNIGN PURPOSE
CHARANKUMARREDDYBOJJ
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
SUFYAN SATTAR
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
Mohit Gupta
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to Spring
Sujit 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 🎸
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservices
Nilanjan Roy
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applications
michaelaaron25322
 
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 - a framework written by developers
Spring - a framework written by developersSpring - a framework written by developers
Spring - a framework written by developers
MarcioSoaresPereira1
 
"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 development
Strannik_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).pdf
Appster1
 
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
Appster1
 
Spring Boot Interview Questions PDF By ScholarHat
Spring Boot Interview Questions PDF By ScholarHatSpring Boot Interview Questions PDF By ScholarHat
Spring Boot Interview Questions PDF By ScholarHat
Scholarhat
 
Springboot - A milestone framework in Java Development
Springboot - A milestone framework in Java DevelopmentSpringboot - A milestone framework in Java Development
Springboot - A milestone framework in Java Development
Expeed Software
 
cadec-2029-SPRING SPRING BOOT LEARNIGN PURPOSE
cadec-2029-SPRING SPRING BOOT LEARNIGN PURPOSEcadec-2029-SPRING SPRING BOOT LEARNIGN PURPOSE
cadec-2029-SPRING SPRING BOOT LEARNIGN PURPOSE
CHARANKUMARREDDYBOJJ
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
SUFYAN SATTAR
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
Mohit Gupta
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to Spring
Sujit 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 🎸
 
Ad

Recently uploaded (20)

Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
Interactive odoo dashboards for sales, CRM , Inventory, Invoice, Purchase, Pr...
AxisTechnolabs
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AIScaling GraphRAG:  Efficient Knowledge Retrieval for Enterprise AI
Scaling GraphRAG: Efficient Knowledge Retrieval for Enterprise AI
danshalev
 
Ad

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"