Author:Karanam, Ranga
No description
Tags
Support Statistics
¥.00 ·
0times
Text Preview (First 20 pages)
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
(This page has no text content)
Page
2
Mastering Spring 5.0 Master reactive programming, microservices, Cloud Native applications, and more This book is based on Spring Version 5.0 RC1 Ranga Rao Karanam BIRMINGHAM - MUMBAI
Page
3
Mastering Spring 5.0 Copyright © 2017 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: June 2017 Production reference: 1240617 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78712-317-5 www.packtpub.com
Page
4
Credits Author Ranga Rao Karanam Copy Editor Stuti Srivastava Reviewer Jarosław Krochmalski Project Coordinator Prajakta Naik Commissioning Editor Kunal Parikh Proofreader Safis Editing Acquisition Editor Denim Pinto Indexer Rekha Nair Content Development Editor Siddhi Chavan Graphics Abhinash Sahu Technical Editor Supriya Thabe Production Coordinator Shraddha Falebhai
Page
5
About the Author Ranga Rao Karanam is a programmer, trainer, and architect. His areas of interest include Cloud Native Applications, microservices, evolutionary design, high-quality code, DevOps, BDD, TDD, and refactoring. He loves consulting for start-ups on developing scalable, component-based Cloud Native applications, and following modern development practices such as BDD, continuous delivery, and DevOps. He loves the freedom the Spring Framework brings to developing enterprise Java applications. Ranga started in28minutes with the vision of creating high-quality courses on developing Cloud Native Java applications. He is looking forward to enhancing his already considerable success--75,000 students on Udemy and 35,000 subscribers on YouTube. Ranga likes to play cricket and go hiking. His dream is to spend a year hiking the Himalayas. My family and best friends – thank you for everything!
Page
6
About the Reviewer Jarosław Krochmalski is a passionate software designer and developer who specializes in the financial business domain. He has over 12 years of experience in software development. He is a clean-code and software craftsmanship enthusiast. He is a Certified ScrumMaster and a fan of Agile. His professional interests include new technologies in web application development, design patterns, enterprise architecture, and integration patterns. He likes to experiment with NoSQL and cloud computing. Jaroslaw has been working with IDEA since its first release and has observed the IDE grow and mature. He has been designing and developing software professionally since 2000 and has been using Java as his primary programming language since 2002. In the past, he worked for companies such as Kredyt Bank (KBC) and Bank BPS on many large-scale projects, such as international money orders, express payments, and collection systems. He currently works as a consultant for the Danish company 7N as an infrastructure architect for the Nykredit bank. You can reach him via Twitter at @jkroch or by email at jarek@finsys.pl. He has authored the books, IntelliJ Idea Essentials, Developing with Docker, and Docker and Kubernetes for Java Developers by Packt, and he has reviewed another book by Packt, Spring Essentials. Hello to all my friends in Finsys, 7N, and Nykredit – keep up the good work!
Page
7
www.PacktPub.com For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. h t t p s ://w w w . p a c k t p u b . c o m /m a p t Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser
Page
8
Customer Feedback Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at h t t p s ://w w w . a m a z o n . c o m /d p /1787123170. If you'd like to join our team of regular reviewers, you can e-mail us at customerreviews@packtpub.com. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Page
9
Table of Contents Preface 1 Chapter 1: Evolution to Spring Framework 5.0 7 Spring Framework 8 Problems with EJB 8 Why is Spring Framework popular? 8 Simplified unit testing 9 Reduction in plumbing code 9 How does Spring Framework do this magic? 10 Architectural flexibility 11 Keep up with changing times 12 Spring modules 12 Spring Core Container 13 Cross-cutting concerns 13 Web 14 Business 14 Data 15 Spring Projects 15 Spring Boot 16 Spring Cloud 16 Spring Data 16 Spring Batch 17 Spring Security 18 Spring HATEOAS 18 New features in Spring Framework 5.0 19 Baseline upgrades 19 JDK 9 runtime compatibility 20 Usage of JDK 8 features in Spring Framework code 20 Reactive programming support 21 Functional web framework 21 Java modularity with Jigsaw 22 Kotlin support 23 Dropped features 24 Spring Boot 2.0 new features 25 Summary 26
Page
10
[ ii ] Chapter 2: Dependency Injection 27 Understanding dependency injection 28 Understanding dependencies 28 The Spring IoC container 31 Defining beans and wiring 31 Creating a Spring IoC container 33 Java configuration for the application context 33 A quick review 34 Launching the application context with Java configuration 35 The console log 36 The XML configuration for the application context 37 Defining the XML Spring configuration 37 Launching an application context with the XML configuration 38 Writing JUnit using the Spring context 38 Unit testing with mocks 40 Container managed beans 42 Dependency injection types 43 The setter injection 43 The constructor injection 44 Constructor versus setter injection 44 Spring bean scopes 44 Java versus XML configuration 45 The @Autowired annotation in depth 46 The @Primary annotation 46 The @Qualifier annotation 47 Other important Spring annotations 47 Exploring Contexts and dependency injection 48 An example of CDI 49 Summary 50 Chapter 3: Building a Web Application with Spring MVC 51 Java web application architecture 52 Model 1 architecture 52 Model 2 architecture 53 Model 2 Front Controller architecture 54 Basic flows 55 Basic setup 55 Adding dependency for Spring MVC 55 Adding DispatcherServlet to web.xml 56 Creating Spring context 57 Flow 1 - Simple controller flow without View 57 Creating a Spring MVC controller 58 Running the web application 58
Page
11
[ iii ] Unit testing 59 Setting up the Controller to test 59 Writing the Test method 60 Flow 2 - Simple controller flow with a View 61 Spring MVC controller 61 Creating a View - a JSP 62 View resolver 62 Unit testing 63 Setting up the Controller to test 63 Writing the Test method 64 Flow 3 - Controller redirecting to a View with Model 64 Spring MVC controller 65 Creating a View 65 Unit testing 66 Setting up the Controller to test 66 Writing the Test method 66 Flow 4 - Controller redirecting to a View with ModelAndView 67 Spring MVC controller 67 Creating a View 68 Unit testing 68 Flow 5 - Controller redirecting to a View with a form 69 Creating a command or form backing object 69 The Controller method to show the form 69 Creating the View with a form 70 Controller get method to handle form submit 72 Unit testing 73 Flow 6 - Adding validation to the previous flow 73 Hibernate Validator dependency 74 Simple validations on the bean 74 Custom validations 75 Unit testing 76 Controller setup 76 The Test method 76 An overview of Spring MVC 77 Important features 77 How it works 78 Important concepts behind Spring MVC 79 RequestMapping 79 Examples of request mapping 79 Example 1 79 Example 2 79 Example 3 80 Request Mapping methods - supported method arguments 81 RequestMapping methods - supported return types 82 View resolution 83 Configuring JSP view resolver 83
Page
12
[ iv ] Configuring Freemarker 84 Handler mappings and Interceptors 84 Defining a HandlerInterceptor 85 Mapping HandlerInterceptor to handlers 86 Model attributes 87 Session attributes 88 Putting an attribute in the session 88 Reading an attribute from the session 88 Removing an attribute from the session 89 InitBinders 89 The @ControllerAdvice annotation 89 Spring MVC - advanced features 90 Exception handling 91 Common exception handling across controllers 91 The error view 92 Specific exception handling in a Controller 93 Internationalization 93 Message bundle setup 94 Configuring a SessionLocaleResolver 94 Configuring a CookieLocaleResolver 95 Integration testing Spring controllers 96 Serving static resources 97 Exposing static content 97 Caching static content 98 Enabling GZip compression of static content 99 Integrating Spring MVC with Bootstrap 100 Bootstrap WebJar as Maven dependency 100 Configure Spring MVC resource handler to deliver WebJar static content 100 Using Bootstrap resources in JSP 101 Spring Security 101 Adding Spring Security dependency 102 Configuring a filter to intercept all requests 102 Logout 104 Summary 105 Chapter 4: Evolution toward Microservices and Cloud-Native Applications 106 Typical web application architecture with Spring 107 Web layer 108 Web application - rendering an HTML View 108 RESTful services 108 Business layer 108 Data layer 109
Page
13
[ v ] Integration layer 109 Cross-cutting concerns 110 Problems solved by Spring 110 Loose coupling and testability 111 Plumbing code 111 Lightweight architecture 112 Architecture flexibility 112 Simplified implementation of cross-cutting concerns 112 Design patterns for free 112 Application development goals 113 Speed 114 Safety 114 Reliability 115 Availability 115 Security 115 Performance 116 High resilience 116 Scalability 116 Challenges with monolithic applications 117 Long release cycles 117 Difficult to scale 118 Adapting new technologies 118 Adapting new methodologies 118 Adapting modern development practices 118 Understanding microservices 118 What is a microservice? 119 The microservice architecture 119 Microservice characteristics 121 Small and lightweight microservices 121 Interoperability with message-based communication 122 Capability-aligned microservices 122 Independently deployable units 122 Stateless 122 Automated build and release process 123 Event-driven architecture 123 Approach 1 - sequential approach 124 Approach 2 - event-driven approach 124 Independent teams 125 Microservice advantages 125 Faster time to market 125 Technology evolution 126 Availability and scaling 126 Team dynamics 127
Page
14
[ vi ] Microservice challenges 127 Increased need for automation 127 Defining the boundaries of subsystems 128 Visibility and monitoring 128 Fault tolerance 129 Eventual consistency 129 Shared capabilities (enterprise level) 129 Increased need for operations teams 130 Cloud-Native applications 130 Twelve-Factor App 131 Maintain one code base 131 Dependencies 131 Config 133 Backing services 134 Build, release, run 134 Stateless 135 Port binding 135 Concurrency 135 Disposability 135 Environment parity 136 Logs as event streams 136 No distinction of admin processes 136 Spring projects 136 Spring Boot 137 Spring Cloud 137 Summary 138 Chapter 5: Building Microservices with Spring Boot 139 What is Spring Boot? 140 Building a quick prototype for a microservice 140 Primary goals 141 Nonfunctional features 141 Spring Boot Hello World 142 Configure spring-boot-starter-parent 142 spring-boot-starter-parent 144 Configure pom.xml with the required starter projects 145 Understanding starter projects 146 Configuring spring-boot-maven-plugin 148 Creating your first Spring Boot launch class 148 SpringApplication class 149 The @SpringBootApplication annotation 149 Running our Hello World application 150 Auto-configuration 152 Starter projects 156
Page
15
[ vii ] What is REST? 158 First REST service 160 Simple method returning string 161 Unit testing 161 Integration testing 162 Simple REST method returning an object 164 Executing a request 164 Unit testing 165 Integration testing 165 Get method with path variables 165 Executing a request 166 Unit testing 167 Integration testing 167 Creating a todo resource 168 Request methods, operations, and URIs 168 Beans and services 169 Retrieving a Todo list 171 Executing the service 171 Unit testing 172 Integration testing 173 Retrieving details for a specific Todo 174 Executing the service 175 Unit testing 175 Integration testing 176 Adding a Todo 176 Postman 177 Executing the POST service 178 Unit testing 179 Integration testing 180 Spring Initializr 181 Creating your first Spring Initializr project 183 pom.xml 185 FirstSpringInitializrApplication.java class 186 FirstSpringInitializrApplicationTests class 186 A quick peek into auto-configuration 186 Summary 189 Chapter 6: Extending Microservices 190 Exception handling 190 Spring Boot default exception handling 190 Nonexistent resource 191 Resource throwing an exception 192 Throwing a custom exception 193 Customizing the exception message 194
Page
16
[ viii ] Response status 196 HATEOAS 197 Sending HATEOAS links in response 199 Spring Boot starter HATEOAS 199 Validation 200 Enabling validation on the controller method 201 Defining validations on the bean 202 Unit testing validations 203 Documenting REST services 203 Generating a Swagger specification 204 Swagger UI 208 Customizing Swagger documentation using annotations 210 Securing REST services with Spring Security 213 Adding Spring Security starter 214 Basic authentication 214 Integration testing 216 Unit testing 217 OAuth 2 authentication 217 High-level flow 218 Implementing OAuth 2 authentication for our service 218 Setting up authorization and resource servers 218 Executing OAuth requests 219 Obtaining an access token 220 Executing the request using the access token 221 Integration test 222 Internationalization 223 Caching 226 Spring-boot-starter-cache 226 Enabling caching 226 Caching data 227 JSR-107 caching annotations 227 Auto-detection order 228 Summary 228 Chapter 7: Advanced Spring Boot Features 229 Externalised configuration 230 Customizing frameworks through application.properties 231 Logging 231 Embedded server configuration 232 Spring MVC 233 Spring starter security 233 Data Sources, JDBC and JPA 233 Other configuration options 234
Page
17
[ ix ] Custom properties in application.properties 235 Configuration properties - type-safe Configuration Management 236 Profiles 239 Profiles-based Bean configuration 240 Other options for application configuration values 240 YAML configuration 241 Embedded servers 243 Switching to Jetty and Undertow 245 Building a WAR file 247 Developer tools 247 Live reload 248 Spring Boot Actuator 249 HAL Browser 251 Configuration properties 252 Environment details 254 Health 255 Mappings 255 Beans 257 Metrics 258 Auto-configuration 259 Debugging 261 Deploying an application to Cloud 261 Cloud Foundry 261 Summary 264 Chapter 8: Spring Data 265 Background - data stores 265 Spring Data 266 Spring Data Commons 267 Repository 267 The CrudRepository interface 268 The PagingAndSortingRepository interface 268 Spring Data JPA 268 Spring Data JPA example 269 New project with Starter Data JPA 269 Entities 270 The SpringBootApplication class 272 Populating some data 274 A simple repository 274 Unit test 275 The CrudRepository interface 276 Unit test 276
Page
18
[ x ] The PagingAndSortingRepository interface 278 Unit tests 278 Query methods 280 Queries 282 Named Parameters 283 Named Query 283 Native query 283 Spring Data Rest 284 The GET method 286 The POST method 286 The search resource 288 Big Data 288 MongoDB 289 Unit test 290 Summary 291 Chapter 9: Spring Cloud 292 Introducing Spring Cloud 292 Spring Cloud Netflix 294 Demo microservices setup 295 Microservice A 296 Service consumer 299 Ports 300 Centralized microservice configuration 301 Problem statement 301 Solution 302 Options 303 Spring Cloud Config 303 Implementing Spring Cloud Config Server 304 Setting up Spring Cloud Config Server 305 Connecting Spring Cloud Config Server to a local Git repository 306 Creating an environment-specific configuration 307 Spring Cloud Config Client 309 Spring Cloud Bus 311 The need for Spring Cloud Bus 311 Propogating configuration changes using Spring Cloud Bus 311 Implementation 312 Declarative REST Client - Feign 314 Load balancing 317 Ribbon 317 Implementation 318 The Name server 320
Page
19
[ xi ] Limitations of hard coding microservice URLs 321 Workings of Name server 321 Options 322 Implementation 322 Setting up a Eureka Server 322 Registering microservices with Eureka 324 Connecting the service consumer microservice with Eureka 326 API Gateways 327 Implementing client-side load balancing with Zuul 328 Setting up a new Zuul API Gateway Server 329 Zuul custom filters 330 Invoking microservices through Zuul 332 Configuring service consumer to use Zuul API gateway 333 Distributed tracing 334 Distributed tracing options 335 Implementing Spring Cloud Sleuth and Zipkin 335 Integrating microservice components with Spring Cloud Sleuth 336 Setting up Zipkin Distributed Tracing Server 338 Integrating microservice components with Zipkin 339 Hystrix - fault tolerance 342 Implementation 342 Summary 343 Chapter 10: Spring Cloud Data Flow 344 Message-based asynchronous communication 344 Complexities of asynchronous communication 346 Spring projects for asynchronous messages 348 Spring Integration 348 Spring Cloud Stream 349 Spring Cloud Data Flow 350 Spring Cloud Stream 351 Spring Cloud Stream architecture 352 Event processing - stock trading example 353 Model for stock trading example 354 The source application 354 Processor 356 Sink 358 Spring Cloud Data Flow 359 High-level architecture 361 Implementing Spring Cloud Data Flow 361 Setting up Spring Cloud Data Flow server 361 Setting up Data Flow Shell project 364 Configuring the apps 367
Page
20
[ xii ] Configuring the stream 369 Deploying the stream 370 Log messages - setting up connections to the message factory 371 Log messages - the flow of events 373 Spring Cloud Data Flow REST APIs 373 Spring Cloud Task 375 Summary 377 Chapter 11: Reactive Programming 378 The Reactive Manifesto 378 Characteristics of Reactive Systems 379 Reactive use case - a stock price page 380 The traditional approach 381 The reactive approach 381 Comparison between the traditional and reactive approaches 382 Reactive programming in Java 384 Reactive streams 384 Reactor 385 Mono 386 Flux 389 Spring Web Reactive 390 Creating a project using Spring Initializr 391 Creating an HTML view 394 Launching SpringReactiveExampleApplication 395 Reactive databases 397 Integrating Spring Boot Reactive MongoDB Starter 398 Creating a model object - a stock document 399 Creating a ReactiveCrudRepository 399 Initialising stock data using the Command Line Runner 400 Creating Reactive methods in Rest Controller 400 Updating the view to subscribe to the event stream 401 Launching SpringReactiveExampleApplication 402 Summary 402 Chapter 12: Spring Best Practices 404 Maven standard directory layout 404 Layered architecture 406 Recommended practices 407 Separate API and impl for important layers 408 Exception handling 409 Spring's approach to exception handling 410 The recommended approach 410 Keeping your Spring configuration light 411
Comments 0
Loading comments...
Reply to Comment
Edit Comment