SlideShare a Scribd company logo
Spring Framework
Petclinic
Michael Isvy
Antoine Rey
Spring Petclinic
 Sample application designed to show how the Spring application frameworks can
be used to build simple, but powerful database-oriented applications
 Demonstrate the use of Spring's core functionality:
 JavaBeans based application configuration using Inversion of Control (IoC)
 Model View Controller (MVC) web Presentation Layer
 Practical database access through JDBC, Java Persistence API (JPA) or Spring Data JPA
 Application monitoring based on JMX
 Declarative Transaction Management using AOP
 Data Validation that supports but is not dependent on the Presentation Layer
 Exists many versions (forks) of the Spring Petclinic sample application
Spring Framework Petclinic
 https://github.com/spring-petclinic/spring-framework-petclinic
 Fork of the « canonical » implementation of Spring Petclinic
 Maintain a Petclinic version with a plain old Spring Framework configuration
and with a 3-layer architecture
3 Spring
profiles
JDBC
JPA (default)
Spring Data JPA
Repository
Service
@Cacheable
@Transactional
Controller
Bean Validation
Spring @MVC
annotations
Views
Bootstrap (CSS)
JSP with
custom tags
custom LESS
webjars
Software Layers
Domain Model
Data Access
VisitRepository
JdbcVisit
RepositoryImpl
JpaVisit
RepositoryImpl
SpringData
VisitRepository
findByPetId: 16 lines of code findByPetId: 3 (short)
lines of code
findByPetId: 0 lines (interface
declaration is enough based
on naming conventions)
In order to select which implementation should be used :
1. select the appropriate bean profile inside PetclinicInitializer (jdbc, jpa or spring-data-jpa)
2. or use the -Dspring.profiles.active=jdbc VM option
Database
# Properties that control the population of schema and data for a new data source
jdbc.initLocation=classpath:db/${db.script}/initDB.sql
jdbc.dataLocation=classpath:db/${db.script}/populateDB.sql
 Supports HSQLDB (default), MySQL, PostgreSQL
 Connections parameters and drivers are declared into Maven profiles
 DDL and DML SQL scripts for each database vendors:
docker run --name mysql-petclinic -e MYSQL_ROOT_PASSWORD=petclinic -e MYSQL_DATABASE=petclinic
-p 3306:3306 mysql:5.7.8
mvn tomcat7:run-war -P MySQL
 How to start Spring Petclinic with a MySQL database?
data-access.properties
Bean profiles
business-config.xml
3 profiles
default (JPA)
jdbc
Spring Data JPA
Inside PetclinicInitializer.javaInside Junit tests
No configuration needed in case you wish to use the default profile (jpa)
@ContextConfiguration(locations = … })
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("jpa")
public class ClinicServiceJpaTests … { }
XmlWebApplicationContext context =
new XmlWebApplicationContext();
context.setConfigLocations(…);
context.getEnvironment().setDefaultProfiles("jpa");
<beans profile="jpa,spring-data-jpa">
<bean id="entityManagerFactory" … >
</beans>
Caching
 The list of Veterinarians is cached using ehcache
ClinicServiceImpl
tools-config.xml
ehcache.xml
@Cacheable(value = "vets")
public Collection<Vet> findVets()
throws DataAccessException {…}
<cache name="vets"
timeToLiveSeconds="60"
maxElementsInMemory="100" …/>
<!-- Enables scanning for @Cacheable annotation -->
<cache:annotation-driven/>
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheCacheManager"
p:cacheManager-ref="ehcache"/>
<bean id="ehcache"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
p:configLocation="classpath:cache/ehcache.xml"/>
Transaction management
<!-- Enables scanning for @Transactional annotations -->
<tx:annotation-driven/>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
@Transactional(readOnly = true)
public Collection<PetType> findPetTypes() throws DataAccessException {
return petRepository.findPetTypes();
}
business-config.xml
ClinicServiceImpl.java
Alternative to JPA,
Transaction Managers
for a single:
JPA
EntityManagerFactory
JDBC
DataSource
Exception Handling
PetRepository
ClinicService
PetController
May throw a RuntimeException
(typically DataAccessException)
Transaction is rolled back
in case of a RuntimeException
(exception is still propagated to PetController)
Exception is not handled there
It is propagated.
SimpleMapping
ExceptionResolver
Declared in mvc-core-config.xml
Based on the configuration used in petclinic:
• Logs the exception stacktrace
• Forwards to WEB-INF/jsp/exception.jsp
• Exception logged as a comment inside exception.jsp
Aspect Oriented Programming (1/2)
 How to add behavior in all methods of all Repository classes?
JpaOwnerRepository
JpaPetRepository
JpaVetRepository
JpaVisitRepository
ClinicService LOG ALL
METHOD
CALLS
Aspect Oriented Programming (2/2)
 CallMonitoringAspect
…
@Repository
public class
JpaVetRepositoryImpl
@Repository
public class
JpaVisitRepositoryImpl
Adds monitoring
Adds
monitoring
Adds monitoring
@Aspect
public class CallMonitoringAspect {
@Around("within(@org.springframework.stereotype.Repository *)")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { … }
To understand further how AOP works in Spring:
https://spring.io/blog/2012/05/23/transactions-caching-and-aop-understanding-proxy-usage-in-spring
View Resolvers in Spring Petclinic
ContentNegotiatingViewResolver Does not resolve any view on its own
Delegates to other view resolvers
BeanName
ViewResolver
JSON and XML
InternalResource
ViewResolver
Default viewClass: JstlView
(used for JSP files)
vets.html
owners.html
vets.xml
vets.json
mvc-view-config.xml
Datatables in Spring MVC
15
JSP file
<table id="vets" class="table table-striped">
<thead>
<tr>
<th>Name</th><th>Address</th><th>City</th><th>Telephone</th><th>Pets</th>
</tr>
</thead>
<tbody>
<c:forEach items="${selections}" var="owner">
<tr>
<td>
<spring:url value="/owners/{ownerId}.html" var="ownerUrl">
<spring:param name="ownerId" value="${owner.id}"/>
</spring:url>
<a href="${fn:escapeXml(ownerUrl)}"><c:out value="${owner.firstName} ${owner.lastName}"/></a>
</td>
<td>
<c:out value="${owner.address}"/>
</td>
…
</tr>
</c:forEach>
</tbody>
</table>
Simple HTML tables with Bootstrap style
Templating
 Simple JSP custom tags
vetList.jsp
Main content
layout.tag
htmlHeader.tag
bodyHeader.tag
pivotal.tag
menu.tag
footer.tag
jquery.js, jquery-ui.js,
bootstrap.js
petclinic.css
Validation
 Server-side validation with Bean Validation
 Few annotations on entities: @Digits, @NotEmpty (Hibernate Validator)
 Custom Spring MVC Validator when required (i.e. PetValidator)
@RequestMapping(value = "/owners/new",
method = RequestMethod.POST)
public String processCreationForm(@Valid Owner owner,
BindingResult result) {
if (result.hasErrors()) { …
public class Owner extends Person {
@Column(name = "address")
@NotEmpty
private String address;
...
<c:if test="${status.error}">
<span class="glyphicon glyphicon-remove
form-control-feedback" aria-hidden="true"/>
<span class="help-inline">${status.errorMessage}</span>
</c:if>
 Allow CSS and JS libraries to be imported as Maven libraries
 Used in Petclinic for jQuery, jQuery-ui, Bootstrap
 http://www.webjars.org/
Webjars
Using Webjars
 Inside pom.xml
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>2.2.4</version>
</dependency>
<mvc:resources mapping="/webjars/**"
location="classpath:/META-INF/resources/webjars/"/>
 Inside JSP (footer.tag)
 Spring MVC configuration
<spring:url value="/webjars/jquery/2.2.4/jquery.min.js" var="jQuery"/>
<script src="${jQuery}"></script>
The Js file is inside a jar file!
 Inside IDE
LESS
 LESS as a CSS pre-processor
 See petclinic.less
 CSS generated by wro4j
 Integrated to the Maven build
 See usage of the wro4j-maven-plugin inside the pom.xml
 Less import from Bootstrap webjar
<groups xmlns="http://www.isdc.ro/wro">
<group name="petclinic">
<css>classpath:META-INF/resources/webjars/
bootstrap/3.3.6/less/bootstrap.less</css>
<css>/petclinic.less</css>
</group>
</groups>
wro.xml
Java based configuration
 Spring XML configuration could be replaced by Java configuration
 Checkout the javaconfig branch
@Configuration
@EnableWebMvc
@Import(MvcViewConfig.class)
@ComponentScan(basePackages =
{ "org.springfrk.samples.petclinic.web" })
public class MvcCoreConfig
extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry reg) {
reg.addViewController("/").setViewName("welcome");
}
…
}
MvcCoreConfig.java
<import resource="mvc-view-config.xml"/>
<context:component-scan
base-package="org.springfrk.samples.petclinic.web"/>
<mvc:annotation-driven />
<mvc:view-controller path="/" view-name="welcome"/>
…
mvc-core-config.xml
Unit Testing
@Test
public void testProcessUpdateFormHasErrors() throws Exception {
mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", 1, 1)
.param("name", "Betty")
.param("birthDate", "2015/02/12"))
.andExpect(model().attributeHasNoErrors("owner"))
.andExpect(model().attributeHasErrors("pet"))
.andExpect(status().isOk())
.andExpect(view().name("pets/createOrUpdatePetForm"));
}
 Frameworks: Spring Test, JUnit, HSQLDB, Mockito,
AssertJ, Hamcrest, Json Path
 Tests are shared between persistence technologies
 Inherits from AbstractClinicServiceTests
PetControllerTests.java
Comparing with the original Spring Petclinic
Spring Framework Petclinic « Canonical » Spring Petclinic
Spring stack Plain Old Spring Framework Spring Boot
Architecture 3 layers Aggregate-oriented domain
Persistence JDBC, JPA, Spring Data JPA Spring Data JPA
View JSP Thymeleaf
Databases support HSQLDB, MySQL, PostgreSQL HSQLDB, MySQL
Containers support Tomcat 7 and 8, Jetty 9 Embbeded Tomcat and Jetty
Java support Java 7 and 8 Java 8
• « Canonical » implementation : https://github.com/spring-projects/spring-petclinic
• Spring Framework version : https://github.com/spring-petclinic/spring-framework-petclinic
Other Spring Petclinic versions
Name Technologies Github
Spring Petclinic Angular AngularJS 1.x, Spring Boot
and Spring Data JPA
https://github.com/spring-
petclinic/spring-petclinic-angular1
Spring Petclinic React ReactJS (with TypeScript) and
Spring Boot
https://github.com/spring-
petclinic/spring-petclinic-reactjs
Spring Petclinic
Microservices
Distributed version of Spring
Petclinic built with Spring
Cloud
https://github.com/spring-
petclinic/spring-petclinic-microservices
References
 Transactions, Caching and AOP: understanding proxy usage in
Spring (Michael Isvy)
 Series of 5 blog entries from on how to Improve performance of
the Spring-Petclinic application (Julien Dubois)
 Exception Handling in Spring MVC (Paul Chapman)
 Spring MVC Test Framework (Rossen Stoyanchev)
 Empower your CSS in your Maven build (Nicolas Frankel)
Ad

More Related Content

What's hot (20)

Spring Boot
Spring BootSpring Boot
Spring Boot
Jiayun Zhou
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
Naphachara Rattanawilai
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
Dzmitry Naskou
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
Eberhard Wolff
 
Quarkus k8s
Quarkus   k8sQuarkus   k8s
Quarkus k8s
Georgios Andrianakis
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
Jeevesh Pandey
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
07.pallav
 
Spring Boot
Spring BootSpring Boot
Spring Boot
HongSeong Jeon
 
Introduction to thymeleaf
Introduction to thymeleafIntroduction to thymeleaf
Introduction to thymeleaf
NexThoughts Technologies
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
Alex Movila
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Pei-Tang Huang
 
Spring Core
Spring CoreSpring Core
Spring Core
Pushan Bhattacharya
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
José Paumard
 
PostgreSQL and JDBC: striving for high performance
PostgreSQL and JDBC: striving for high performancePostgreSQL and JDBC: striving for high performance
PostgreSQL and JDBC: striving for high performance
Vladimir Sitnikov
 
Microservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring CloudMicroservice With Spring Boot and Spring Cloud
Microservice With Spring Boot and Spring Cloud
Eberhard Wolff
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
Jonathan Holloway
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 

Similar to Spring Framework Petclinic sample application (20)

Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
Michael Plöd
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qcon
Yiwei Ma
 
Dropwizard
DropwizardDropwizard
Dropwizard
Scott Leberknight
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
Michał Orman
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
Ted Pennings
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
Joshua Long
 
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparison
Jini Lee
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
Tuna Tore
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
Josué Neis
 
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
 
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
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
Joshua Long
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
Spiffy
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Arun Gupta
 
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
varunsunny21
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
Michael Plöd
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qcon
Yiwei Ma
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
Michał Orman
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
Ted Pennings
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
Joshua Long
 
Javatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparisonJavatwo2012 java frameworkcomparison
Javatwo2012 java frameworkcomparison
Jini Lee
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
Tuna Tore
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
Josué Neis
 
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
 
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
 
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#31.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
Joshua Long
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
Spiffy
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Arun Gupta
 
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
varunsunny21
 
Ad

More from Antoine Rey (13)

Quoi de neuf à Devoxx France 2017 ?
Quoi de neuf à Devoxx France 2017 ?Quoi de neuf à Devoxx France 2017 ?
Quoi de neuf à Devoxx France 2017 ?
Antoine Rey
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
Antoine Rey
 
Les Streams de Java 8
Les Streams de Java 8Les Streams de Java 8
Les Streams de Java 8
Antoine Rey
 
Retours Devoxx France 2016
Retours Devoxx France 2016Retours Devoxx France 2016
Retours Devoxx France 2016
Antoine Rey
 
Ces outils qui vous font gagner du temps
Ces outils qui vous font gagner du tempsCes outils qui vous font gagner du temps
Ces outils qui vous font gagner du temps
Antoine Rey
 
Tester unitairement une application java
Tester unitairement une application javaTester unitairement une application java
Tester unitairement une application java
Antoine Rey
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
Antoine Rey
 
Introduction à Angular JS
Introduction à Angular JSIntroduction à Angular JS
Introduction à Angular JS
Antoine Rey
 
Workshop Spring - Session 5 - Spring Integration
Workshop Spring - Session 5 - Spring IntegrationWorkshop Spring - Session 5 - Spring Integration
Workshop Spring - Session 5 - Spring Integration
Antoine Rey
 
Workshop Spring - Session 4 - Spring Batch
Workshop Spring -  Session 4 - Spring BatchWorkshop Spring -  Session 4 - Spring Batch
Workshop Spring - Session 4 - Spring Batch
Antoine Rey
 
Workshop Spring 3 - Tests et techniques avancées du conteneur Spring
Workshop Spring  3 - Tests et techniques avancées du conteneur SpringWorkshop Spring  3 - Tests et techniques avancées du conteneur Spring
Workshop Spring 3 - Tests et techniques avancées du conteneur Spring
Antoine Rey
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications Java
Antoine Rey
 
Workshop Spring - Session 1 - L'offre Spring et les bases
Workshop Spring  - Session 1 - L'offre Spring et les basesWorkshop Spring  - Session 1 - L'offre Spring et les bases
Workshop Spring - Session 1 - L'offre Spring et les bases
Antoine Rey
 
Quoi de neuf à Devoxx France 2017 ?
Quoi de neuf à Devoxx France 2017 ?Quoi de neuf à Devoxx France 2017 ?
Quoi de neuf à Devoxx France 2017 ?
Antoine Rey
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
Antoine Rey
 
Les Streams de Java 8
Les Streams de Java 8Les Streams de Java 8
Les Streams de Java 8
Antoine Rey
 
Retours Devoxx France 2016
Retours Devoxx France 2016Retours Devoxx France 2016
Retours Devoxx France 2016
Antoine Rey
 
Ces outils qui vous font gagner du temps
Ces outils qui vous font gagner du tempsCes outils qui vous font gagner du temps
Ces outils qui vous font gagner du temps
Antoine Rey
 
Tester unitairement une application java
Tester unitairement une application javaTester unitairement une application java
Tester unitairement une application java
Antoine Rey
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
Antoine Rey
 
Introduction à Angular JS
Introduction à Angular JSIntroduction à Angular JS
Introduction à Angular JS
Antoine Rey
 
Workshop Spring - Session 5 - Spring Integration
Workshop Spring - Session 5 - Spring IntegrationWorkshop Spring - Session 5 - Spring Integration
Workshop Spring - Session 5 - Spring Integration
Antoine Rey
 
Workshop Spring - Session 4 - Spring Batch
Workshop Spring -  Session 4 - Spring BatchWorkshop Spring -  Session 4 - Spring Batch
Workshop Spring - Session 4 - Spring Batch
Antoine Rey
 
Workshop Spring 3 - Tests et techniques avancées du conteneur Spring
Workshop Spring  3 - Tests et techniques avancées du conteneur SpringWorkshop Spring  3 - Tests et techniques avancées du conteneur Spring
Workshop Spring 3 - Tests et techniques avancées du conteneur Spring
Antoine Rey
 
Workshop spring session 2 - La persistance au sein des applications Java
Workshop spring   session 2 - La persistance au sein des applications JavaWorkshop spring   session 2 - La persistance au sein des applications Java
Workshop spring session 2 - La persistance au sein des applications Java
Antoine Rey
 
Workshop Spring - Session 1 - L'offre Spring et les bases
Workshop Spring  - Session 1 - L'offre Spring et les basesWorkshop Spring  - Session 1 - L'offre Spring et les bases
Workshop Spring - Session 1 - L'offre Spring et les bases
Antoine Rey
 
Ad

Recently uploaded (20)

DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 

Spring Framework Petclinic sample application

  • 2. Spring Petclinic  Sample application designed to show how the Spring application frameworks can be used to build simple, but powerful database-oriented applications  Demonstrate the use of Spring's core functionality:  JavaBeans based application configuration using Inversion of Control (IoC)  Model View Controller (MVC) web Presentation Layer  Practical database access through JDBC, Java Persistence API (JPA) or Spring Data JPA  Application monitoring based on JMX  Declarative Transaction Management using AOP  Data Validation that supports but is not dependent on the Presentation Layer  Exists many versions (forks) of the Spring Petclinic sample application
  • 3. Spring Framework Petclinic  https://github.com/spring-petclinic/spring-framework-petclinic  Fork of the « canonical » implementation of Spring Petclinic  Maintain a Petclinic version with a plain old Spring Framework configuration and with a 3-layer architecture
  • 4. 3 Spring profiles JDBC JPA (default) Spring Data JPA Repository Service @Cacheable @Transactional Controller Bean Validation Spring @MVC annotations Views Bootstrap (CSS) JSP with custom tags custom LESS webjars Software Layers
  • 6. Data Access VisitRepository JdbcVisit RepositoryImpl JpaVisit RepositoryImpl SpringData VisitRepository findByPetId: 16 lines of code findByPetId: 3 (short) lines of code findByPetId: 0 lines (interface declaration is enough based on naming conventions) In order to select which implementation should be used : 1. select the appropriate bean profile inside PetclinicInitializer (jdbc, jpa or spring-data-jpa) 2. or use the -Dspring.profiles.active=jdbc VM option
  • 7. Database # Properties that control the population of schema and data for a new data source jdbc.initLocation=classpath:db/${db.script}/initDB.sql jdbc.dataLocation=classpath:db/${db.script}/populateDB.sql  Supports HSQLDB (default), MySQL, PostgreSQL  Connections parameters and drivers are declared into Maven profiles  DDL and DML SQL scripts for each database vendors: docker run --name mysql-petclinic -e MYSQL_ROOT_PASSWORD=petclinic -e MYSQL_DATABASE=petclinic -p 3306:3306 mysql:5.7.8 mvn tomcat7:run-war -P MySQL  How to start Spring Petclinic with a MySQL database? data-access.properties
  • 8. Bean profiles business-config.xml 3 profiles default (JPA) jdbc Spring Data JPA Inside PetclinicInitializer.javaInside Junit tests No configuration needed in case you wish to use the default profile (jpa) @ContextConfiguration(locations = … }) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("jpa") public class ClinicServiceJpaTests … { } XmlWebApplicationContext context = new XmlWebApplicationContext(); context.setConfigLocations(…); context.getEnvironment().setDefaultProfiles("jpa"); <beans profile="jpa,spring-data-jpa"> <bean id="entityManagerFactory" … > </beans>
  • 9. Caching  The list of Veterinarians is cached using ehcache ClinicServiceImpl tools-config.xml ehcache.xml @Cacheable(value = "vets") public Collection<Vet> findVets() throws DataAccessException {…} <cache name="vets" timeToLiveSeconds="60" maxElementsInMemory="100" …/> <!-- Enables scanning for @Cacheable annotation --> <cache:annotation-driven/> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehcache"/> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:cache/ehcache.xml"/>
  • 10. Transaction management <!-- Enables scanning for @Transactional annotations --> <tx:annotation-driven/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entityManagerFactory-ref="entityManagerFactory"/> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/> @Transactional(readOnly = true) public Collection<PetType> findPetTypes() throws DataAccessException { return petRepository.findPetTypes(); } business-config.xml ClinicServiceImpl.java Alternative to JPA, Transaction Managers for a single: JPA EntityManagerFactory JDBC DataSource
  • 11. Exception Handling PetRepository ClinicService PetController May throw a RuntimeException (typically DataAccessException) Transaction is rolled back in case of a RuntimeException (exception is still propagated to PetController) Exception is not handled there It is propagated. SimpleMapping ExceptionResolver Declared in mvc-core-config.xml Based on the configuration used in petclinic: • Logs the exception stacktrace • Forwards to WEB-INF/jsp/exception.jsp • Exception logged as a comment inside exception.jsp
  • 12. Aspect Oriented Programming (1/2)  How to add behavior in all methods of all Repository classes? JpaOwnerRepository JpaPetRepository JpaVetRepository JpaVisitRepository ClinicService LOG ALL METHOD CALLS
  • 13. Aspect Oriented Programming (2/2)  CallMonitoringAspect … @Repository public class JpaVetRepositoryImpl @Repository public class JpaVisitRepositoryImpl Adds monitoring Adds monitoring Adds monitoring @Aspect public class CallMonitoringAspect { @Around("within(@org.springframework.stereotype.Repository *)") public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { … } To understand further how AOP works in Spring: https://spring.io/blog/2012/05/23/transactions-caching-and-aop-understanding-proxy-usage-in-spring
  • 14. View Resolvers in Spring Petclinic ContentNegotiatingViewResolver Does not resolve any view on its own Delegates to other view resolvers BeanName ViewResolver JSON and XML InternalResource ViewResolver Default viewClass: JstlView (used for JSP files) vets.html owners.html vets.xml vets.json mvc-view-config.xml
  • 15. Datatables in Spring MVC 15 JSP file <table id="vets" class="table table-striped"> <thead> <tr> <th>Name</th><th>Address</th><th>City</th><th>Telephone</th><th>Pets</th> </tr> </thead> <tbody> <c:forEach items="${selections}" var="owner"> <tr> <td> <spring:url value="/owners/{ownerId}.html" var="ownerUrl"> <spring:param name="ownerId" value="${owner.id}"/> </spring:url> <a href="${fn:escapeXml(ownerUrl)}"><c:out value="${owner.firstName} ${owner.lastName}"/></a> </td> <td> <c:out value="${owner.address}"/> </td> … </tr> </c:forEach> </tbody> </table> Simple HTML tables with Bootstrap style
  • 16. Templating  Simple JSP custom tags vetList.jsp Main content layout.tag htmlHeader.tag bodyHeader.tag pivotal.tag menu.tag footer.tag jquery.js, jquery-ui.js, bootstrap.js petclinic.css
  • 17. Validation  Server-side validation with Bean Validation  Few annotations on entities: @Digits, @NotEmpty (Hibernate Validator)  Custom Spring MVC Validator when required (i.e. PetValidator) @RequestMapping(value = "/owners/new", method = RequestMethod.POST) public String processCreationForm(@Valid Owner owner, BindingResult result) { if (result.hasErrors()) { … public class Owner extends Person { @Column(name = "address") @NotEmpty private String address; ... <c:if test="${status.error}"> <span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"/> <span class="help-inline">${status.errorMessage}</span> </c:if>
  • 18.  Allow CSS and JS libraries to be imported as Maven libraries  Used in Petclinic for jQuery, jQuery-ui, Bootstrap  http://www.webjars.org/ Webjars
  • 19. Using Webjars  Inside pom.xml <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>2.2.4</version> </dependency> <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>  Inside JSP (footer.tag)  Spring MVC configuration <spring:url value="/webjars/jquery/2.2.4/jquery.min.js" var="jQuery"/> <script src="${jQuery}"></script> The Js file is inside a jar file!  Inside IDE
  • 20. LESS  LESS as a CSS pre-processor  See petclinic.less  CSS generated by wro4j  Integrated to the Maven build  See usage of the wro4j-maven-plugin inside the pom.xml  Less import from Bootstrap webjar <groups xmlns="http://www.isdc.ro/wro"> <group name="petclinic"> <css>classpath:META-INF/resources/webjars/ bootstrap/3.3.6/less/bootstrap.less</css> <css>/petclinic.less</css> </group> </groups> wro.xml
  • 21. Java based configuration  Spring XML configuration could be replaced by Java configuration  Checkout the javaconfig branch @Configuration @EnableWebMvc @Import(MvcViewConfig.class) @ComponentScan(basePackages = { "org.springfrk.samples.petclinic.web" }) public class MvcCoreConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry reg) { reg.addViewController("/").setViewName("welcome"); } … } MvcCoreConfig.java <import resource="mvc-view-config.xml"/> <context:component-scan base-package="org.springfrk.samples.petclinic.web"/> <mvc:annotation-driven /> <mvc:view-controller path="/" view-name="welcome"/> … mvc-core-config.xml
  • 22. Unit Testing @Test public void testProcessUpdateFormHasErrors() throws Exception { mockMvc.perform(post("/owners/{ownerId}/pets/{petId}/edit", 1, 1) .param("name", "Betty") .param("birthDate", "2015/02/12")) .andExpect(model().attributeHasNoErrors("owner")) .andExpect(model().attributeHasErrors("pet")) .andExpect(status().isOk()) .andExpect(view().name("pets/createOrUpdatePetForm")); }  Frameworks: Spring Test, JUnit, HSQLDB, Mockito, AssertJ, Hamcrest, Json Path  Tests are shared between persistence technologies  Inherits from AbstractClinicServiceTests PetControllerTests.java
  • 23. Comparing with the original Spring Petclinic Spring Framework Petclinic « Canonical » Spring Petclinic Spring stack Plain Old Spring Framework Spring Boot Architecture 3 layers Aggregate-oriented domain Persistence JDBC, JPA, Spring Data JPA Spring Data JPA View JSP Thymeleaf Databases support HSQLDB, MySQL, PostgreSQL HSQLDB, MySQL Containers support Tomcat 7 and 8, Jetty 9 Embbeded Tomcat and Jetty Java support Java 7 and 8 Java 8 • « Canonical » implementation : https://github.com/spring-projects/spring-petclinic • Spring Framework version : https://github.com/spring-petclinic/spring-framework-petclinic
  • 24. Other Spring Petclinic versions Name Technologies Github Spring Petclinic Angular AngularJS 1.x, Spring Boot and Spring Data JPA https://github.com/spring- petclinic/spring-petclinic-angular1 Spring Petclinic React ReactJS (with TypeScript) and Spring Boot https://github.com/spring- petclinic/spring-petclinic-reactjs Spring Petclinic Microservices Distributed version of Spring Petclinic built with Spring Cloud https://github.com/spring- petclinic/spring-petclinic-microservices
  • 25. References  Transactions, Caching and AOP: understanding proxy usage in Spring (Michael Isvy)  Series of 5 blog entries from on how to Improve performance of the Spring-Petclinic application (Julien Dubois)  Exception Handling in Spring MVC (Paul Chapman)  Spring MVC Test Framework (Rossen Stoyanchev)  Empower your CSS in your Maven build (Nicolas Frankel)

Editor's Notes

  • #3: Source: http://docs.spring.io/docs/petclinic.html
  • #5: Hibernate as JPA provider
  • #8: DDL and DML scripts depends from the database
  • #20: Possibly: show that we can outsource from a variable