Spring Boot - Tutorialspoint

Transcription

Spring Boot

Spring BootAbout the TutorialSpring Boot is an open source Java-based framework used to create a Micro Service. It isdeveloped by Pivotal Team. It is easy to create a stand-alone and production ready springapplications using Spring Boot. Spring Boot contains a comprehensive infrastructuresupport for developing a microservice and enables you to develop enterprise-readyapplications that you can “just run”.AudienceThis tutorial is designed for Java developers to understand and develop production-readyspring applications with minimum configurations. It explores major features of Spring Bootsuch as Starters, Auto-configuration, Beans, Actuator and more.By the end of this tutorial, you will gain an intermediate level of expertise in Spring Boot.PrerequisitesThis tutorial is written for readers who have a prior experience of Java, Spring, Maven,and Gradle. You can easily understand the concepts of Spring Boot if you have knowledgeon these concepts. It would be an additional advantage if you have an idea about writinga RESTful Web Service. If you are a beginner, we suggest you to go through tutorialsrelated to these concepts before you start with Spring Boot.Copyright and Disclaimer Copyright 2018 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I)Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republishany contents or a part of contents of this e-book in any manner without written consentof the publisher.We strive to update the contents of our website and tutorials as timely and as precisely aspossible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of ourwebsite or its contents including this tutorial. If you discover any errors on our website orin this tutorial, please notify us at contact@tutorialspoint.comi

Spring BootTable of ContentsAbout the Tutorial . iAudience . iPrerequisites . iCopyright and Disclaimer . iTable of Contents . ii1. SPRING BOOT – INTRODUCTION . 1What is Micro Service?. 1What is Spring Boot?. 1Why Spring Boot? . 2How does it work? . 2Spring Boot Starters . 2Auto Configuration . 3Spring Boot Application . 4Component Scan . 42. SPRING BOOT – QUICK START . 6Prerequisites . 6Spring Boot CLI . 63. SPRING BOOT – BOOTSTRAPPING . 8Spring Initializer . 8Maven. 9Gradle . 10Class Path Dependencies . 11Main Method . 12Write a Rest Endpoint . 12Create an Executable JAR . 13ii

Spring BootRun Hello World with Java . 144. SPRING BOOT – TOMCAT DEPLOYMENT . 16Spring Boot Servlet Initializer . 16Setting Main Class . 17Update packaging JAR into WAR . 17Packaging your Application . 19Deploy into Tomcat. 205. SPRING BOOT – BUILD SYSTEMS . 25Dependency Management . 25Maven Dependency . 25Gradle Dependency . 266. SPRING BOOT – CODE STRUCTURE. 27Default package . 27Typical Layout . 276. SPRING BOOT – CODE STRUCTURE. 277. SPRING BOOT – SPRING BEANS AND DEPENDENCY INJECTION . 288. SPRING BOOT – RUNNERS . 29Application Runner . 29Command Line Runner . 309. SPRING BOOT – APPLICATION PROPERTIES . 31Command Line Properties . 31Properties File . 31YAML File . 31Externalized Properties . 32Use of @Value Annotation . 32iii

Spring BootSpring Boot Active Profile . 3310. SPRING BOOT – LOGGING . 37Log Format . 37Console Log Output. 37File Log Output . 37Log Levels . 38Configure Logback. 3811. SPRING BOOT – BUILDING RESTFUL WEB SERVICES . 41Rest Controller . 43Request Mapping . 43Request Body . 44Path Variable . 44Request Parameter . 44GET API . 44POST API . 46PUT API . 47DELETE API . 4812. SPRING BOOT – EXCEPTION HANDLING . 54Controller Advice . 54Exception Handler . 5413. SPRING BOOT – INTERCEPTOR . 6214. SPRING BOOT – SERVLET FILTER. 7115. SPRING BOOT – TOMCAT PORT NUMBER . 77Custom Port . 77Random Port . 77iv

Spring Boot16. SPRING BOOT – REST TEMPLATE . 78GET . 79POST . 80PUT . 81DELETE . 8217. SPRING BOOT – FILE HANDLING . 89File Upload . 89File Download . 9018. SPRING BOOT – SERVICE COMPONENTS . 9619. SPRING BOOT – THYMELEAF . 106Thymeleaf Templates . 106Web Application . 10620. SPRING BOOT – CONSUMING RESTFUL WEB SERVICES . 113Angular JS . 12221. SPRING BOOT – CORS SUPPORT . 124Enable CORS in Controller Method . 124Global CORS Configuration . 12422. SPRING BOOT – INTERNATIONALIZATION . 126Dependencies . 126LocaleResolver . 126LocaleChangeInterceptor . 127Messages Sources . 127HTML file . 12823. SPRING BOOT – SCHEDULING . 134Java Cron Expression . 134v

Spring BootFixed Rate . 135Fixed Delay . 13624. SPRING BOOT – ENABLING HTTPS . 138Self-Signed Certificate . 138Configure HTTPS . 13925. SPRING BOOT – EUREKA SERVER . 140Building a Eureka Server . 14026. SPRING BOOT – SERVICE REGISTRATION WITH EUREKA . 14627. SPRING BOOT – ZUUL PROXY SERVER AND ROUTING. 153Creating Zuul Server Application . 15328. SPRING BOOT – SPRING CLOUD CONFIGURATION SERVER . 160Creating Spring Cloud Configuration Server . 16029. SPRING BOOT – SPRING CLOUD CONFIGURATION CLIENT . 166Working with Spring Cloud Configuration Server . 16630. SPRING BOOT – ACTUATOR . 169Enabling Spring Boot Actuator . 16931. SPRING BOOT – ADMIN SERVER . 17132. SPRING BOOT – ADMIN CLIENT . 17633. SPRING BOOT – ENABLING SWAGGER2. 17934. SPRING BOOT – CREATING DOCKER IMAGE . 186Create Dockerfile . 186Maven. 186Gradle . 19035. SPRING BOOT – TRACING MICRO SERVICE LOGS . 194vi

Spring BootSpring Cloud Sleuth . 194Zipkin Server . 19936. SPRING BOOT – FLYWAY DATABASE . 206Configuring Flyway Database . 20637. SPRING BOOT – SENDING EMAIL . 21338. SPRING BOOT – HYSTRIX . 21939. SPRING BOOT – WEB SOCKET. 22640. SPRING BOOT – BATCH SERVICE. 23541. SPRING BOOT – SPRING FOR APACHE KAFKA . 244Producing Messages . 244Consuming a Message . 24542. SPRING BOOT – TWILIO. 252Sending SMS . 252Voice Calls . 25743. SPRING BOOT – UNIT TEST CASES . 262Mockito . 26244. SPRING BOOT – REST CONTROLLER UNIT TEST . 269Writing a Unit Test for REST Controller . 26945. SPRING BOOT – DATABASE HANDLING . 276Connect to H2 database . 276Connect MySQL. 277Connect Redis . 279JDBCTemplate . 280Multiple DataSource . 280vii

Spring Boot46. SPRING BOOT – SECURING WEB APPLICATIONS . 284Securing a Web application . 28447. SPRING BOOT SECURITY – OAUTH2 WITH JWT . 294Authorization Server . 294Resource Server . 294OAuth2 . 294JWT Token . 29448. SPRING BOOT – GOOGLE CLOUD PLATFORM . 311Google Cloud SQL . 31449. SPRING BOOT – GOOGLE OAUTH2 SIGN-IN . 316viii

1. Spring Boot – IntroductionSpring BootSpring Boot is an open source Java-based framework used to create a micro Service. It isdeveloped by Pivotal Team and is used to build stand-alone and production ready springapplications. This chapter will give you an introduction to Spring Boot and familiarizes youwith its basic concepts.What is Micro Service?Micro Service is an architecture that allows the developers to develop and deploy servicesindependently. Each service running has its own process and this achieves the lightweightmodel to support business applications.AdvantagesMicro services offers the following advantages to its developers: Easy deployment Simple scalability Compatible with Containers Minimum configuration Lesser production timeWhat is Spring Boot?Spring Boot provides a good platform for Java developers to develop a stand-alone andproduction-grade spring application that you can just run. You can get started withminimum configurations without the need for an entire Spring configuration setup.AdvantagesSpring Boot offers the following advantages to its developers: Easy to understand and develop spring applications Increases productivity Reduces the development timeGoalsSpring Boot is designed with the following goals: To avoid complex XML configuration in Spring To develop a production ready Spring applications in an easier way To reduce the development time and run the application independently Offer an easier way of getting started with the application1

Spring BootWhy Spring Boot?You can choose Spring Boot because of the features and benefits it offers as given here: It provides a flexible way to configure Java Beans, XML configurations, and DatabaseTransactions. It provides a powerful batch processing and manages REST endpoints. In Spring Boot, everything is auto configured; no manual configurations are needed. It offers annotation-based spring application Eases dependency management It includes Embedded Servlet ContainerHow does it work?Spring Boot automatically configures your application based on the dependencies you haveadded to the project by using @EnableAutoConfiguration annotation. For example, ifMySQL database is on your classpath, but you have not configured any databaseconnection, then Spring Boot auto-configures an in-memory database.The entry point of the spring boot application is@SpringBootApplication annotation and the main method.theclasscontainsSpring Boot automatically scans all the components included in the project by using@ComponentScan annotation.Spring Boot StartersHandling dependency management is a difficult task for big projects. Spring Boot resolvesthis problem by providing a set of dependencies for developers convenience.For example, if you want to use Spring and JPA for database access, it is sufficient if youinclude spring-boot-starter-data-jpa dependency in your project.Note that all Spring Boot starters follow the same naming pattern spring-boot-starter*, where * indicates that it is a type of the application.ExamplesLook at the following Spring Boot starters explained below for a better understanding:Spring Boot Starter Actuator dependency is used to monitor and manage yourapplication. Its code is shown below: dependency groupId org.springframework.boot /groupId artifactId spring-boot-starter-actuator /artifactId /dependency 2

Spring BootSpring Boot Starter Security dependency is used for Spring Security. Its code is shownbelow: dependency groupId org.springframework.boot /groupId artifactId spring-boot-starter-security /artifactId /dependency Spring Boot Starter web dependency is used to write a Rest Endpoints. Its code isshown below: dependency groupId org.springframework.boot /groupId artifactId spring-boot-starter-web /artifactId /dependency Spring Boot Starter Thyme Leaf dependency is used to create a web application. Itscode is shown below: dependency groupId org.springframework.boot /groupId artifactId spring-boot-starter-thymeleaf /artifactId /dependency Spring Boot Starter Test dependency is used for writing Test cases. Its code is shownbelow: dependency groupId org.springframework.boot /groupId artifactId spring-boot-starter-test /artifactId /dependency Auto ConfigurationSpring Boot Auto Configuration automatically configures your Spring application based onthe JAR dependencies you added in the project. For example, if MySQL database is on yourclass path, but you have not configured any database connection, then Spring Boot autoconfigures an in-memory database.For this purpose, you need to add @EnableAutoConfiguration annotation or@SpringBootApplication annotation to your main class file. Then, your Spring Bootapplication will be automatically configured.3

Spring BootObserve the following code for a better understanding:import org.springframework.boot.SpringApplication;import onfiguration;@EnableAutoConfigurationpublic class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}Spring Boot ApplicationThe entry point of the Spring Boot Application is the class contains@SpringBootApplication annotation. This class should have the main method to run theSpring Boot application. @SpringBootApplication annotation includes AutoConfiguration, Component Scan, and Spring Boot Configuration.If you added @SpringBootApplication annotation to the class, you do not need to addthe @EnableAutoConfiguration, @ComponentScan and @SpringBootConfigurationannotation.

2 Why Spring Boot? You can choose Spring Boot because of the features and benefits it offers as given here: It provides a flexible way to configure Java Beans, XML configurations, and Database Transactions. It provides a powerful batch processing and manages REST endpoints.