📄 Page
1
M A N N I N G LAURENŢIU SPILCĂ FOREWORD BY VICTOR RENTEA LEARN WHAT YOU NEED AND LEARN IT WELL
📄 Page
2
Business logic code Transactions Security Logging Caching Data transfer Data persistence Use the Spring IoC container to manage object instances easier and glue in other functionalities Spring provides. Use Spring Data to connect to the SQL and NoSQL databases your backend app uses to persist the data. Use Spring Integration or Spring for Apache Kafka to more easily send messages to your JMS or Kafka topics. Use Spring Security to implement the authentication and authorization configurations. Use Spring Boot to ease the complexity of your configurations and write less code to implement the app. Use Spring MVC or Spring WebFlux to implement the REST endpoints called by the client apps or other backend solutions. Figure 1 The user’s perspective is similar to viewing an iceberg. Users mainly observe the results of the business logic code, but this is only a small part of what builds the app’s complete functionality. Like an iceberg that is mostly underwater and hidden from view, we don't see most of the code in an enterprise app because it's provided by dependencies. Figure 2 The possibilities of using Spring in a backend application are nearly endless, and include exposing functionalities that other applications can call, managing the database access, securing the application, and managing integration through third-party message brokers.
📄 Page
3
Spring Start Here LEARN WHAT YOU NEED AND LEARN IT WELL LAURENŢIU SPILCĂ FOREWORD BY VICTOR RENTEA M A N N I N G SHELTER ISLAND
📄 Page
4
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2021 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Marina Michaels 20 Baldwin Road Technical development editor: Al Scherer PO Box 761 Review editor: Mihaela Batinić Shelter Island, NY 11964 Production editor: Andy Marinkovich Copy editor: Michele Mitchell Proofreader: Keri Hales Technical proofreader: Jean-François Morin Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN 9781617298691 Printed in the United States of America
📄 Page
5
iii brief contents PART 1 FUNDAMENTALS................................................................1 1 ■ Spring in the real world 3 2 ■ The Spring context: Defining beans 22 3 ■ The Spring context: Wiring beans 50 4 ■ The Spring context: Using abstractions 75 5 ■ The Spring context: Bean scopes and life cycle 99 6 ■ Using aspects with Spring AOP 121 PART 2 IMPLEMENTATION .........................................................151 7 ■ Understanding Spring Boot and Spring MVC 153 8 ■ Implementing web apps with Spring Boot and Spring MVC 176 9 ■ Using the Spring web scopes 199 10 ■ Implementing REST services 224 11 ■ Consuming REST endpoints 245 12 ■ Using data sources in Spring apps 264 13 ■ Using transactions in Spring apps 284 14 ■ Implementing data persistence with Spring Data 302 15 ■ Testing your Spring app 323
📄 Page
6
(This page has no text content)
📄 Page
7
v contents foreword xi preface xiii acknowledgments xv about this book xvii about the author xxi about the cover illustration xxii PART 1 FUNDAMENTALS ......................................................1 1 Spring in the real world 3 1.1 Why should we use frameworks? 4 1.2 The Spring ecosystem 7 Discovering Spring Core: The foundation of Spring 8 ■ Using Spring Data Access feature to implement the app’s persistence 10 The Spring MVC capabilities for developing web apps 10 ■ The Spring testing feature 10 ■ Projects from the Spring ecosystem 10 1.3 Spring in real-world scenarios 12 Using Spring in the development of a backend app 12 ■ Using Spring in a test automation app 14 ■ Using Spring for the development of a desktop app 16 ■ Using Spring in mobile apps 16
📄 Page
8
CONTENTSvi 1.4 When not to use frameworks 17 You need to have a small footprint 17 ■ Security needs dictate custom code 18 ■ Abundant existing customizations make a framework impractical 18 ■ You won’t benefit from switching to a framework 18 1.5 What will you learn in this book 19 2 The Spring context: Defining beans 22 2.1 Creating a Maven project 23 2.2 Adding new beans to the Spring context 29 Using the @Bean annotation to add beans into the Spring context 33 ■ Using stereotype annotations to add beans to the Spring context 41 ■ Programmatically adding beans to the Spring context 45 3 The Spring context: Wiring beans 50 3.1 Implementing relationships among beans defined in the configuration file 51 Wiring the beans using a direct method call between the @Bean methods 55 ■ Wiring the beans using the @Bean annotated method’s parameters 58 3.2 Using the @Autowired annotation to inject beans 61 Using @Autowired to inject the values through the class fields 61 Using @Autowired to inject the values through the constructor 64 Using dependency injection through the setter 65 3.3 Dealing with circular dependencies 66 3.4 Choosing from multiple beans in the Spring context 68 4 The Spring context: Using abstractions 75 4.1 Using interfaces to define contracts 76 Using interfaces for decoupling implementations 76 ■ The requirement of the scenario 79 ■ Implementing the requirement without using a framework 80 4.2 Using dependency injection with abstractions 85 Deciding which objects should be part of the Spring context 85 Choosing what to auto-wire from multiple implementations of an abstraction 91 4.3 Focusing on object responsibilities with stereotype annotations 96
📄 Page
9
CONTENTS vii 5 The Spring context: Bean scopes and life cycle 99 5.1 Using the singleton bean scope 100 How singleton beans work 100 ■ Singleton beans in real-world scenarios 107 ■ Using eager and lazy instantiation 108 5.2 Using the prototype bean scope 111 How prototype beans work 111 ■ Prototype beans in real-world scenarios 115 6 Using aspects with Spring AOP 121 6.1 How aspects work in Spring 123 6.2 Implementing aspects with Spring AOP 126 Implementing a simple aspect 127 ■ Altering the intercepted method’s parameters and the returned value 135 ■ Intercepting annotated methods 140 ■ Other advice annotations you can use 143 6.3 The aspect execution chain 144 PART 2 IMPLEMENTATION ...............................................151 7 Understanding Spring Boot and Spring MVC 153 7.1 What is a web app? 154 A general overview of a web app 155 ■ Different fashions of implementing a web app with Spring 156 ■ Using a servlet container in web app development 159 7.2 The magic of Spring Boot 162 Using a project initialization service to create a Spring Boot project 162 ■ Using dependency starters to simplify the dependency management 168 ■ Using autoconfiguration by convention based on dependencies 169 7.3 Implementing a web app with Spring MVC 170 8 Implementing web apps with Spring Boot and Spring MVC 176 8.1 Implementing web apps with a dynamic view 177 Getting data on the HTTP request 182 ■ Using request parameters to send data from client to server 183 ■ Using path variables to send data from client to server 187 8.2 Using the GET and POST HTTP methods 189
📄 Page
10
CONTENTSviii 9 Using the Spring web scopes 199 9.1 Using the request scope in a Spring web app 201 9.2 Using the session scope in a Spring web app 209 9.3 Using the application scope in a Spring web app 218 10 Implementing REST services 224 10.1 Using REST services to exchange data between apps 226 10.2 Implementing a REST endpoint 227 10.3 Managing the HTTP response 231 Sending objects as a response body 232 ■ Setting the response status and headers 234 ■ Managing exceptions at the endpoint level 237 10.4 Using a request body to get data from the client 242 11 Consuming REST endpoints 245 11.1 Calling REST endpoints using Spring Cloud OpenFeign 249 11.2 Calling REST endpoints using RestTemplate 253 11.3 Calling REST endpoints using WebClient 256 12 Using data sources in Spring apps 264 12.1 What a data source is 265 12.2 Using JdbcTemplate to work with persisted data 269 12.3 Customizing the configuration of the data source 278 Defining the data source in the application properties file 279 Using a custom DataSource bean 280 13 Using transactions in Spring apps 284 13.1 Transactions 287 13.2 How transactions work in Spring 289 13.3 Using transactions in Spring apps 291 14 Implementing data persistence with Spring Data 302 14.1 What Spring Data is 303 14.2 How Spring Data works 306 14.3 Using Spring Data JDBC 311
📄 Page
11
CONTENTS ix 15 Testing your Spring app 323 15.1 Writing correctly implemented tests 325 15.2 Implementing tests in Spring apps 327 Implementing unit tests 328 ■ Implementing integration tests 341 appendix A Architectural approaches 347 appendix B Using XML for the context configuration 358 appendix C A quick introduction to HTTP 360 appendix D Using JSON formatting 369 appendix E Installing MySQL and creating a database 372 appendix F Recommended tools 380 appendix G Recommended learning materials for further study 382 index 385
📄 Page
12
(This page has no text content)
📄 Page
13
xi foreword Born as an alternative to EJBs in the early 2000s, the Spring framework quickly over- took its opponent with the simplicity of its programming model, the variety of its fea- tures, and its third-party library integrations. The Spring ecosystem grew over the years into the broadest and most mature development framework available in any pro- gramming language. Its main competitor quit the race when Oracle stopped the evo- lution of Java EE 8, and the community took over its maintenance via Jakarta EE. According to recent surveys (http://mng.bz/l9VB and http://mng.bz/B1Ar), Spring is the framework underlying more than half of the Java applications. This fact builds up an enormous codebase that makes it critical for any Java developer to learn Spring, as it’s inevitable you’ll encounter this technology in your career. I’ve been developing applications with Spring for 15 years, and today the teams that I train in hundreds of companies are almost all using Spring. The reality is that despite being so popular, it’s pretty hard to find quality introduc- tory material. The reference documentation is thousands of pages long, describing all the subtleties and details that could be helpful in very specific scenarios, so it’s not an option for a newcomer. While online videos and tutorials typically fail to engage the student, very few books capture the essence of Spring framework, often spending long pages debating topics that prove to be irrelevant to the problems faced in modern application development. With this book, however, it’s very hard to find anything to remove; all the concepts covered are recurring topics in the development of any Spring application.
📄 Page
14
FOREWORDxii The reader is gently brought to a level sufficient to become rapidly productive in a project based on the Spring framework. My own experience training thousands of employees showed me that the vast majority of developers working with Spring today don’t see the ideas as clearly as this book paints them. Furthermore, developers are unaware of the many pitfalls about which this book warns its readers. In my opinion, this book is a must-read for any developer starting on their first Spring project. The attention with which Laurenţiu anticipates the typical questions occurring in the reader’s mind proves his extensive experience teaching Spring in class. This teach- ing fluency allows the author to adopt a personal, warm tone that makes this book an effortless and pleasant read. The book has a clear, sharp structure, and I really loved how complex topics were progressively revealed and explained and reiterated in sub- sequent chapters. This book shines in that the reader is also introduced to fundamental concerns regarding a legacy project using the Spring framework. In an ecosystem dominated by Spring Boot, I find it very useful to sneak a peek under the hood. On the other end, the book also gently introduces the reader to last-generation technologies, like Feign clients and even reactive programming. I wish you a pleasant reading, and never hesitate to get your hands dirty with some code whenever you think things get complicated. —VICTOR RENTEA JAVA CHAMPION, TRAINER, AND CONSULTANT
📄 Page
15
xiii preface Sharing knowledge and creating learning material is a hobby for me. In addition to being a software developer, I’m also a teacher. As a Java trainer since 2009, I’ve taught Java to thousands of developers with various levels of experience, from university stu- dents to experienced developers in large corporations. In the past few years, I’ve come to consider Spring a must-learn for beginners. Apps today are no longer imple- mented with vanilla languages—almost everything relies on frameworks. Since Spring is the most popular application framework in the Java world today, Spring is some- thing a developer needs to learn in their first software development steps. In teaching Spring to beginners, I’ve realized that it is still treated as something you learn only when you already have some experience coding. When I started writing Spring Start Here, there were already plenty of tutorials, books, and articles on the topic, but my students continued to tell me they found those materials hard to under- stand. I realized the problem was not that the existing learning material wasn’t excel- lent, but that there was no dedicated study guide for an absolute beginner, so I decided to write a book that doesn’t consider Spring something you learn after you have some experience, but instead something you can learn with minimal founda- tional knowledge. Technology changes quickly. But it’s not only the technology changing. We also need to consider how we can improve the way we teach these technologies. Some years ago, one would start learning the language fundamentals and get employed as a developer without even knowing what a framework is. But today, these things are different. Learning all the details of a language up-front is no longer the way to quickly
📄 Page
16
PREFACExiv develop the skills you need to work in a software development team. Now, I recommend developers start with the fundamentals and, once they feel comfortable with the basics, start learning an application framework. Spring is, in my opinion, the best application framework to start learning. Understanding the Spring basics also opens doors to learning other technologies and changes the old, linear learning approach into something that looks more like a tree—and each branch of the tree is a new framework you learn in parallel with others. I designed Spring Start Here to be the book you want to start learning the Spring framework with. This book leads you step-by-step, providing you with all the essential theoretical knowledge, accompanied by examples that practically apply the discussed topics. I hope this book will bring significant value to you, the reader, and help you quickly boost your Spring knowledge and open doors for further learning.
📄 Page
17
xv acknowledgments This book wouldn’t be possible without the large number of smart, professional, and friendly people who helped me throughout its development process. First, a big thank you to my wife, Daniela, who was always there for me, and whose valuable opinions, continuous support, and encouragement were a huge help to me. I’d also like to express my gratitude and send special thanks to all the colleagues and friends who helped me from the very first table of contents and proposal with their valuable advice. A big thank you goes to the entire Manning team for their huge help in making this book a reality. I especially want to recognize Marina Michaels, Al Scherer, and Jean-François Morin for always being incredibly supportive and professional. Your advice has brought great value to this book. I’d like to thank my friend Ioana Göz for the drawings she created for the book. She turned my thoughts into the cartoons in the book. I also want to express my appreciation to all the reviewers who provided such useful feedback at every step. To Alain Lompo, Aleksandr Karpenko, Andrea Carlo Granata, Andrea Paciolla, Andres Damian Sacco, Andrew Oswald, Bobby Lin, Bonnie Malec, Christian Kreutzer-Beck, Daniel Carl, David Lisle Orpen, DeUndre’ Rushon, Harinath Kuntamukkala, Håvard Wall, Jérôme Baton, Jim Welch, João Miguel Pires Dias, Lucian Enache, Matt D., Matthew Greene, Mikael Byström, Mladen Knežić, Nathan B.
📄 Page
18
ACKNOWLEDGMENTSxvi Crocker, Pierre-Michel Ansel, Rajesh Mohanan, Ricardo Di Pasquale, Sunita Chowd- hury, Tan Wee, and Zoheb Ainapore, your input has made this a much better book. Finally, a special thank you to my friends, Maria Chiţu, Andreea Tudose, Florin Ciuculescu, and Daniela Ileana for advising me along the way.
📄 Page
19
xvii about this book Since you’ve opened this book, I assume you’re a software developer in the Java eco- system who found out it’s useful to learn Spring. This book teaches you the Spring foundations, assuming you know nothing in the first place about frameworks and, of course, about Spring. You’ll start with what a framework is and then gradually learn the basics of Spring with applied examples. You will not only learn to use the framework’s components and capabilities, but you’ll also learn the essentials of what happens behind the scenes in these capabilities. Knowing how the framework operates when you use a particular component helps you design better apps, and solve problems faster. When you finish this book, you’ll have learned the following skills, which are highly relevant in implementing apps: ■ Configuring and using the Spring context and dependency injection with Spring ■ Designing and using aspects ■ Implementing web apps ■ Implementing data exchange between apps ■ Persisting data ■ Testing implementations You’ll find this book is valuable for the following: ■ Working on an app using Spring for your job ■ Succeeding in a technical interview for a Java developer role ■ Obtaining your Spring certification
📄 Page
20
ABOUT THIS BOOKxviii Even if this book’s first purpose is not to prepare you for a Spring certification, I con- sider it a must-read before digging into details a certification exam typically requires. Who should read this book This book is for developers who understand basic object-oriented programming and Java concepts and want to learn Spring or refresh their Spring fundamentals knowl- edge. You do not need to have previous experience with any framework, but you need to understand Java because this is the language we use throughout the book’s examples. Spring is one of the most encountered technologies in Java apps and will most likely be used even more in the future. For a Java developer, this makes Spring a must- know today. Learning what I teach you in this book will help you upskill, provide you with the Spring foundation knowledge and skills you need to successfully pass a Java interview, and work on an app using Spring technologies. The book also opens doors to further study Spring details that are more complex. How this book is organized: A roadmap This book is divided into two parts that cover 15 chapters. We’ll start our discussion (in the first part of the book) with straightforward examples to show you how to make Spring aware of your application. We’ll then build examples that enable you to under- stand the core of any real-world Spring app. Once we finish with Spring Core basics, we’ll discuss Spring Data and Spring Boot basics. From chapter 2 to the end of this book, you’ll find that theoretical aspects are accompanied by projects in which we apply the notions we discuss. I explain the code in these examples snippet by snippet. My recommendation is you build these exam- ples with me while reading. Then, you can compare your result with my solution. As presented in the following figure, I designed the book’s chapters to be read in the given order. In chapters 2 through 5, where we discuss the Spring context, you might find the examples predominantly theoretical. For anyone with little or no expe- rience with Spring, it’s essential to start this way. Don’t worry! I present the founda- tions in the easiest possible way, and then our examples and discussions gradually become more sophisticated to reflect real-world, production-ready code. Figure 1 If you start with no (or very little) knowledge about Spring, the best way to read the book is to start with the first chapter and read everything in order. Introduction Chapter 1 The Spring context Chapters 2 through 5 Spring aspects Chapter 6 Spring Web Chapters 7 through 9 REST services Chapters 10 and 11 Persisting data Chapters 12 through 14 Testing Chapter 15