SlideShare a Scribd company logo
1 of 36
Download to read offline
Rediscovering Spring with
Spring Boot
Gunith Devasurendra
Asso. Tech Lead, CMS
Agenda
● Intro
● Using Maven
● Features and Conventions
● Spring Data with Boot
● Spring MVC with Boot
● Spring Test with Boot
● In Conclusion
Intro
Spring
● What?
● Who?
● Why?
● Why not?
● What is Boot?
Spring is a beast!
Spring.. Boot?
Spring made Simple
‘Spring Boot makes it easy to create stand-alone,
production-grade Spring based Applications that you can
“just run”’
New recommended way of running Spring programs
Goals
● Faster and more accessible initial setup
● Default Configurations and the ability to Customize
● No code generation and No XML configs
System Requirements
● Java 6+ (8 recommended)
● Spring 4.1.5+
That's it! Simply include the appropriate spring-boot-*.jar
files on your classpath.
---
● But, Recommended to use Build scripts:
○ Maven (3.2+), Gradle (1.12+)
● Also, Out-of-box supported Servlet containers:
○ Tomcat 7+, Jetty 8+, Undertow 1.1
Using Maven
Using Maven : Parent POM & Dependency
Inherit from the spring-boot-starter-parent project to
obtain sensible defaults:
Java 6 compiler, UTF-8 code, Sensible resource filtering (ex:
for application.properties), Sensible plugin configs
spring-boot-starter-parent extends from spring-boot-
dependencies which holds a predefined set of dependencies.
● Could easily include dependencies from the parent
● Could override the versions by overriding MVN variables
<properties>
<java.version>1.8</java.version>
</properties>
Using Maven : Starter POMs
Starter POMs are a set of convenient dependency descriptors
that you can include in your application
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> ^-- No need for version as it comes
</dependencies> from Parent POM
Has many more including:
spring-boot-starter-amqp, spring-boot-starter-batch,
spring-boot-starter-data-jpa, spring-boot-starter-data-rest,
spring-boot-starter-mail, spring-boot-starter-mobile,
spring-boot-starter-test, spring-boot-starter-logging,
spring-boot-starter-ws spring-security-oauth2
Build File Generation
https://start.spring.io/
Features and Conventions
Main Class
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Just starts up deamon. To build CLI apps, use Spring Boot
CLI
SpringApplication can be customized by calling different
setters
Ex: Command line params, add listeners, shutdown hooks
@SpringBootApplication
}
Code Structure
@ComponentScan automatically picks up all Spring components
com
+- example
+- myproject
+- Application.java <- Main application class is in a
| root package above other classes
+- domain for correct @ComponentScan
| +- Customer.java
| +- CustomerRepository.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
Defining Beans in @Configuration
Spring Boot favors Java-based @Configuration over XML
Config, which is more traditional.
@Configuration
public class AdsdaqCoreDatasourceConfiguration {
@Bean(name = “dataSourceMain”)
@ConfigurationProperties(prefix = “datasource.main”)
@Primary
public DataSource dataSourceAdServer() {
return DataSourceBuilder.create().build();
}
}
___
datasource.main.url=jdbc:mysql://localhost:3306/reviewdb
datasource.main.username=root
datasource.main.password=admin
Enabling Auto Configuration
@EnableAutoConfiguration attempts to automatically configure
the application based on the dependencies
At any point you can start to define your own @Configuration
to replace specific parts of the auto-configuration.
Ex: if you add your own DataSource bean, the default
embedded database support will back away.
There are factories defined in
[MVN_repo]orgspringframeworkbootspring-boot-autoconfigure[VER]
[JAR]META-INFspring.factories
These factories only loaded by if satisfied various
conditions (ex: WebMvcAutoConfiguration)
Spring Beans
Spring provides the following stereotypes for a Spring Bean:
| Annotation | Meaning |
+-------------+-----------------------------------------------------+
| @Component | generic stereotype for any Spring-managed component |
| @Repository | stereotype for persistence layer |
| @Service | stereotype for service layer |
| @Controller | stereotype for presentation layer (spring-mvc) |
Any object with a stereotype as above is identified as a
Spring Bean.
Spring will create them upon container startup and map them
to any @Autowired annotation on an attribute/constructor
Spring Config files
Usually Spring Configuration is stored in file
config/application.properties (or YAML)
Can hard-code values into setters in beans
app.name=MyApp
app.description=${app.name} is a Spring Boot application
This can be overridden by
● runtime variables,
● environment variables,
● profile specific files (application-local.properties),
● based on the location of application.properties,
etc.
Setting Spring Config values to Beans
app.name=MyApp
listener.enable: true
connection.username:
admin
connection.remote-
address: 192.168.1.1
@Value("${app.name}")
private String name;
@Component
@ConditionalOnProperty(prefix = "listener",
name = "enable", matchIfMissing = false)
public class SomeListener { .. }
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
private String username;
@NotNull
private InetAddress remoteAddress;
// ... getters and setters
}
Spring Profiles
Support profiles where the application would act differently
based on the active profile.
Ex: if ‘dev’ profile is passed via env. var.
--spring.profiles.active=dev
If exists,
● Beans with @Profile("dev") will be activated
● File application-dev.properties will be activated
Good for: Dev vs Prod settings, Local Dev vs Default
settings
Logging
Spring uses Commons Logging as default.
By default logs to console unless logging.file or logging.
path is set in application.properties.
Set log levels as follows:
logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
If custom logging framework specific configs are to be used
property logging.config
Log format also can be configured.
Building JAR and Running
Spring has plugins for Eclipse, IDEA etc.
Spring Boot has a Maven plugin that can package the project
as an executable jar. Add the plugin to your <plugins>
section if you want to use it:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
Run java -jar target/myproject-0.0.1-SNAPSHOT.jar
Or mvn spring-boot:run
Spring Data with Boot
DB Access with Spring
If you use embeded DB, it only needs MVN dependency.
If you use a production database,
Spring will connection pooling using tomcat-jdbc by
default (via Starters)
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
There are many more attributes
Data Access Using JPA and Spring Data - Entity
Using spring-boot-starter-data-jpa.
@Entity classes are ‘scanned’.
import javax.persistence.*;
@Entity
public class City implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
}
More info about JPA at Hibernate Documentation
Data Access Using JPA and Spring Data - Repository
SQL are autogenerated.
public interface CityRepository extends PagingAndSortingRepository<City, Long>
{
Page<City> findAll(Pageable pageable);
City findByNameAndCountryAllIgnoringCase(String name, String country);
@Query("select c from City c")
Stream<City> findAllByCustomQueryAndStream();
}
● Repository’s subclass CrudRepository generates default
CRUD methods in runtime.
● CrudRepository’s subclass PagingAndSortingRepository
generates paging and sorting methods
Spring Data REST
Is able to easily open a REST interface to the DB using
Spring Data REST by including a spring-boot-starter-data-
rest dependency
Auto serialization
@RepositoryRestResource(collectionResourceRel = "cities", path =
"cities")
interface CityRepository extends Repository<City, Long> {
...
}
Spring MVC with Boot
Spring MVC
Spring Boot comes with some auto configuration.
@Controller
@RequestMapping(value="/users")
public class MyRestController {
@RequestMapping(value="/{user}/cust", method=RequestMethod.GET)
ModelAndView getUserCustomers(@PathVariable Long user) {
// ...
}
}
@RestController creates a REST service.
● Expects any static content to be in a directory called
/static (or /public or /resources or /META-INF/resources)
or at spring.resources.staticLocations
● /error mapping by default that handles all errors as a
global error page.
@RequestMapping
@RequestMapping when added to a class would be prefixed to
the @RequestMapping of the method
@RequestMapping method can be called with different
parameters and different return types and it will work
differently
Can also write @RequestMapping to be caught based on,
● RequestMethod (GET, POST..)
● HTTP parameters (ex: params="myParam=myValue")
● HTTP Headers (ex: headers="myHeader=myValue")
Spring MVC : Other features
● Templating: Auto-configuration support for: FreeMarker,
Groovy, Thymeleaf, Velocity, Mustache
○ Templates will be picked up automatically from
src/main/resources/templates
● Other REST Implementations: Support for JAX-RS and Jersey
● Embedded servlet container support: Comes with Starter
Pom. Embeds Tomcat by default. Can go for Jetty, and
Undertow servers as well
○ Can set attributes server.port (default is 8080), server.
address, server.session.timeout values
○ Can deploy as a WAR as well
Spring Test with Boot
Why need Spring for Tests?
Sometimes we need Spring context
Ex: DB related tests, Web related tests
Can set custom properties for tests using
@TestPropertySource
Has Transaction support, esp for Integration testing for
Auto-rollback
For TestNG, extend AbstractTransactionalTestNGSpringContextTests
In Conclusion
Parting notes
● Can convert your classic Spring app to Spring Boot
● Many guides found in: http://spring.io/guides
● Well documented
___
Pros
● Easy to use. Will soon be the Future
Cons
● Debugging config issues can get tough. Not much help yet
from ‘Googling’
Thank you

More Related Content

Similar to dokumen.tips_rediscovering-spring-with-spring-boot1.pdf

Meetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfMeetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfLuca Mattia Ferrari
 
Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qconYiwei Ma
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroOndrej Mihályi
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroPayara
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroPayara
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSGunnar Hillert
 
Spring5 New Features
Spring5 New FeaturesSpring5 New Features
Spring5 New FeaturesJay Lee
 
Spring 3 - Der dritte Frühling
Spring 3 - Der dritte FrühlingSpring 3 - Der dritte Frühling
Spring 3 - Der dritte FrühlingThorsten Kamann
 
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...Ivanti
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest servicesIoan Eugen Stan
 
SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitMike Pfaff
 
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 applicationsmichaelaaron25322
 
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.1Michał Orman
 

Similar to dokumen.tips_rediscovering-spring-with-spring-boot1.pdf (20)

Meetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdfMeetup 2022 - APIs with Quarkus.pdf
Meetup 2022 - APIs with Quarkus.pdf
 
Spring boot
Spring bootSpring boot
Spring boot
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Spring design-juergen-qcon
Spring design-juergen-qconSpring design-juergen-qcon
Spring design-juergen-qcon
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara Micro
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara Micro
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara Micro
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
 
Spring5 New Features
Spring5 New FeaturesSpring5 New Features
Spring5 New Features
 
Resthub lyonjug
Resthub lyonjugResthub lyonjug
Resthub lyonjug
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring 3 - Der dritte Frühling
Spring 3 - Der dritte FrühlingSpring 3 - Der dritte Frühling
Spring 3 - Der dritte Frühling
 
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
UEMB200: Next Generation of Endpoint Management Architecture and Discovery Se...
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
SCR Annotations for Fun and Profit
SCR Annotations for Fun and ProfitSCR Annotations for Fun and Profit
SCR Annotations for Fun and Profit
 
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
 
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
 

Recently uploaded

AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 

dokumen.tips_rediscovering-spring-with-spring-boot1.pdf

  • 1. Rediscovering Spring with Spring Boot Gunith Devasurendra Asso. Tech Lead, CMS
  • 2. Agenda ● Intro ● Using Maven ● Features and Conventions ● Spring Data with Boot ● Spring MVC with Boot ● Spring Test with Boot ● In Conclusion
  • 4. Spring ● What? ● Who? ● Why? ● Why not? ● What is Boot?
  • 5. Spring is a beast!
  • 6. Spring.. Boot? Spring made Simple ‘Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”’ New recommended way of running Spring programs Goals ● Faster and more accessible initial setup ● Default Configurations and the ability to Customize ● No code generation and No XML configs
  • 7. System Requirements ● Java 6+ (8 recommended) ● Spring 4.1.5+ That's it! Simply include the appropriate spring-boot-*.jar files on your classpath. --- ● But, Recommended to use Build scripts: ○ Maven (3.2+), Gradle (1.12+) ● Also, Out-of-box supported Servlet containers: ○ Tomcat 7+, Jetty 8+, Undertow 1.1
  • 9. Using Maven : Parent POM & Dependency Inherit from the spring-boot-starter-parent project to obtain sensible defaults: Java 6 compiler, UTF-8 code, Sensible resource filtering (ex: for application.properties), Sensible plugin configs spring-boot-starter-parent extends from spring-boot- dependencies which holds a predefined set of dependencies. ● Could easily include dependencies from the parent ● Could override the versions by overriding MVN variables <properties> <java.version>1.8</java.version> </properties>
  • 10. Using Maven : Starter POMs Starter POMs are a set of convenient dependency descriptors that you can include in your application <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ^-- No need for version as it comes </dependencies> from Parent POM Has many more including: spring-boot-starter-amqp, spring-boot-starter-batch, spring-boot-starter-data-jpa, spring-boot-starter-data-rest, spring-boot-starter-mail, spring-boot-starter-mobile, spring-boot-starter-test, spring-boot-starter-logging, spring-boot-starter-ws spring-security-oauth2
  • 13. Main Class @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } Just starts up deamon. To build CLI apps, use Spring Boot CLI SpringApplication can be customized by calling different setters Ex: Command line params, add listeners, shutdown hooks @SpringBootApplication }
  • 14. Code Structure @ComponentScan automatically picks up all Spring components com +- example +- myproject +- Application.java <- Main application class is in a | root package above other classes +- domain for correct @ComponentScan | +- Customer.java | +- CustomerRepository.java | +- service | +- CustomerService.java | +- web +- CustomerController.java
  • 15. Defining Beans in @Configuration Spring Boot favors Java-based @Configuration over XML Config, which is more traditional. @Configuration public class AdsdaqCoreDatasourceConfiguration { @Bean(name = “dataSourceMain”) @ConfigurationProperties(prefix = “datasource.main”) @Primary public DataSource dataSourceAdServer() { return DataSourceBuilder.create().build(); } } ___ datasource.main.url=jdbc:mysql://localhost:3306/reviewdb datasource.main.username=root datasource.main.password=admin
  • 16. Enabling Auto Configuration @EnableAutoConfiguration attempts to automatically configure the application based on the dependencies At any point you can start to define your own @Configuration to replace specific parts of the auto-configuration. Ex: if you add your own DataSource bean, the default embedded database support will back away. There are factories defined in [MVN_repo]orgspringframeworkbootspring-boot-autoconfigure[VER] [JAR]META-INFspring.factories These factories only loaded by if satisfied various conditions (ex: WebMvcAutoConfiguration)
  • 17. Spring Beans Spring provides the following stereotypes for a Spring Bean: | Annotation | Meaning | +-------------+-----------------------------------------------------+ | @Component | generic stereotype for any Spring-managed component | | @Repository | stereotype for persistence layer | | @Service | stereotype for service layer | | @Controller | stereotype for presentation layer (spring-mvc) | Any object with a stereotype as above is identified as a Spring Bean. Spring will create them upon container startup and map them to any @Autowired annotation on an attribute/constructor
  • 18. Spring Config files Usually Spring Configuration is stored in file config/application.properties (or YAML) Can hard-code values into setters in beans app.name=MyApp app.description=${app.name} is a Spring Boot application This can be overridden by ● runtime variables, ● environment variables, ● profile specific files (application-local.properties), ● based on the location of application.properties, etc.
  • 19. Setting Spring Config values to Beans app.name=MyApp listener.enable: true connection.username: admin connection.remote- address: 192.168.1.1 @Value("${app.name}") private String name; @Component @ConditionalOnProperty(prefix = "listener", name = "enable", matchIfMissing = false) public class SomeListener { .. } @Component @ConfigurationProperties(prefix="connection") public class ConnectionSettings { private String username; @NotNull private InetAddress remoteAddress; // ... getters and setters }
  • 20. Spring Profiles Support profiles where the application would act differently based on the active profile. Ex: if ‘dev’ profile is passed via env. var. --spring.profiles.active=dev If exists, ● Beans with @Profile("dev") will be activated ● File application-dev.properties will be activated Good for: Dev vs Prod settings, Local Dev vs Default settings
  • 21. Logging Spring uses Commons Logging as default. By default logs to console unless logging.file or logging. path is set in application.properties. Set log levels as follows: logging.level.root=WARN logging.level.org.springframework.web=DEBUG If custom logging framework specific configs are to be used property logging.config Log format also can be configured.
  • 22. Building JAR and Running Spring has plugins for Eclipse, IDEA etc. Spring Boot has a Maven plugin that can package the project as an executable jar. Add the plugin to your <plugins> section if you want to use it: <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> Run java -jar target/myproject-0.0.1-SNAPSHOT.jar Or mvn spring-boot:run
  • 24. DB Access with Spring If you use embeded DB, it only needs MVN dependency. If you use a production database, Spring will connection pooling using tomcat-jdbc by default (via Starters) spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driver-class-name=com.mysql.jdbc.Driver There are many more attributes
  • 25. Data Access Using JPA and Spring Data - Entity Using spring-boot-starter-data-jpa. @Entity classes are ‘scanned’. import javax.persistence.*; @Entity public class City implements Serializable { @Id @GeneratedValue private Long id; @Column(nullable = false) private String name; } More info about JPA at Hibernate Documentation
  • 26. Data Access Using JPA and Spring Data - Repository SQL are autogenerated. public interface CityRepository extends PagingAndSortingRepository<City, Long> { Page<City> findAll(Pageable pageable); City findByNameAndCountryAllIgnoringCase(String name, String country); @Query("select c from City c") Stream<City> findAllByCustomQueryAndStream(); } ● Repository’s subclass CrudRepository generates default CRUD methods in runtime. ● CrudRepository’s subclass PagingAndSortingRepository generates paging and sorting methods
  • 27. Spring Data REST Is able to easily open a REST interface to the DB using Spring Data REST by including a spring-boot-starter-data- rest dependency Auto serialization @RepositoryRestResource(collectionResourceRel = "cities", path = "cities") interface CityRepository extends Repository<City, Long> { ... }
  • 29. Spring MVC Spring Boot comes with some auto configuration. @Controller @RequestMapping(value="/users") public class MyRestController { @RequestMapping(value="/{user}/cust", method=RequestMethod.GET) ModelAndView getUserCustomers(@PathVariable Long user) { // ... } } @RestController creates a REST service. ● Expects any static content to be in a directory called /static (or /public or /resources or /META-INF/resources) or at spring.resources.staticLocations ● /error mapping by default that handles all errors as a global error page.
  • 30. @RequestMapping @RequestMapping when added to a class would be prefixed to the @RequestMapping of the method @RequestMapping method can be called with different parameters and different return types and it will work differently Can also write @RequestMapping to be caught based on, ● RequestMethod (GET, POST..) ● HTTP parameters (ex: params="myParam=myValue") ● HTTP Headers (ex: headers="myHeader=myValue")
  • 31. Spring MVC : Other features ● Templating: Auto-configuration support for: FreeMarker, Groovy, Thymeleaf, Velocity, Mustache ○ Templates will be picked up automatically from src/main/resources/templates ● Other REST Implementations: Support for JAX-RS and Jersey ● Embedded servlet container support: Comes with Starter Pom. Embeds Tomcat by default. Can go for Jetty, and Undertow servers as well ○ Can set attributes server.port (default is 8080), server. address, server.session.timeout values ○ Can deploy as a WAR as well
  • 33. Why need Spring for Tests? Sometimes we need Spring context Ex: DB related tests, Web related tests Can set custom properties for tests using @TestPropertySource Has Transaction support, esp for Integration testing for Auto-rollback For TestNG, extend AbstractTransactionalTestNGSpringContextTests
  • 35. Parting notes ● Can convert your classic Spring app to Spring Boot ● Many guides found in: http://spring.io/guides ● Well documented ___ Pros ● Easy to use. Will soon be the Future Cons ● Debugging config issues can get tough. Not much help yet from ‘Googling’