121119THE BEGINNING OF A BEGINNING OF THE BEGINNING OF A TREND
Beginning Spring - download.e-bookshelf.de...Beginning Spring ForewordS . ... Twitter @mertcal....
Transcript of Beginning Spring - download.e-bookshelf.de...Beginning Spring ForewordS . ... Twitter @mertcal....
Beginning Spring
ForewordS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi
chapter 1 POJO Programming Model, Lightweight Containers, and
Inversion of Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
chapter 2 Dependency Injection with Spring . . . . . . . . . . . . . . . . . . . . . . . . . . 17
chapter 3 Building Web Applications Using Spring MVC . . . . . . . . . . . . . . . . . 63
chapter 4 JDBC Data Access with Spring . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
chapter 5 Data Access with JPA Using Spring . . . . . . . . . . . . . . . . . . . . . . . . 137
chapter 6 Managing Transactions with Spring . . . . . . . . . . . . . . . . . . . . . . . . 175
chapter 7 Test‐Driven Development with Spring . . . . . . . . . . . . . . . . . . . . . . 209
chapter 8 Aspect‐Oriented Programming with Spring . . . . . . . . . . . . . . . . . . 237
chapter 9 Spring Expression Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
chapter 10 Caching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
chapter 11 RESTful Web Services with Spring . . . . . . . . . . . . . . . . . . . . . . . . . 305
chapter 12 Securing Web Applications with Spring Security . . . . . . . . . . . . . . 331
chapter 13 Next Stop: Spring 4 .0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
appendix Solutions to Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
Beginning
Spring
Beginning
Spring
Mert ÇalıskanKenan Sevindik
Beginning Spring
Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com
Copyright © 2015 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-89292-3 ISBN: 978-1-118-89303-6 (ebk) ISBN: 978-1-118-89311-1 (ebk)
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or pro-motional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the pub-lisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2014954686
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with any product or vendor mentioned in this book.
This is for you, Love.
—Mert Çaliskan
To my Mom, and to the memory of my Dad...
—Kenan Sevindik
aBout the authorS
Mert ÇaliSkan is a Principle Software Architect living in Ankara, Turkey. He has more than 10 years of expertise in software development with the architectural design of Enterprise Java web applications. Çalıskan is an open source advocate for software projects such as PrimeFaces, and he is the co‐author of PrimeFaces Cookbook, first and second editions (Packt Publishing, 2013). He is the founder of AnkaraJUG, which is the most active JUG in Turkey. Çalıskan is part‐time lecturer at Hacettepe University about Enterprise Web Applications’ Architecture and Web Services. In 2014, he achieved the title of Java Champion. He shares his knowledge at national and international conferences such as JDays 2015, JavaOne 2013, JDC2010, and JSFDays’08. You can follow him on Twitter @mertcal.
kenan Sevindik specializes in architecting and developing enterprise applications using vari-ous Java technologies. His experience with Java dates back to 1998 when he started developing Java applets for online education programs at his university. He has been working with Spring Application Framework and Spring Security Framework since their initial phases. Sevindik has a bachelor’s degree in computer engineering. Currently he works with Harezmi IT Solutions, where he develops enterprise software and gives training, mentoring, and consulting services about Java, OOP, AOP, Spring, Spring Security, and Hibernate all over the world. You can read his technical writings at http://blog.harezmi.com.tr and reach him at [email protected].
aBout the technical editor
chád (Shod) darBy is an author, instructor, and speaker in the Java development world. As a recognized authority on Java applications and architectures, he has presented technical sessions at software development conferences worldwide. In his fifteen years as a professional software architect, he’s had the opportunity to work for Blue Cross/Blue Shield, Merck, Boeing, Red Hat and a handful of startup companies. Chád is a contributing author to several Java books, including Professional Java E‐Commerce (Wiley, 2001) and Beginning Java Networking (Wiley, 2001). Chád has Java certifications from Sun Microsystems and IBM. He holds a B.S. in Computer Science from Carnegie Mellon University. Visit Chád’s blog at www.luv2code.com to view his free video tutorials on Java. You can also follow him on Twitter @darbyluvs2code.
creditS
project editorCharlotte Kughen
technical editorsChád Darby Krishna Srinivasan
production editorRebecca Anderson
copy editorKim Cofer
Manager of content development and assemblyMary Beth Wakefield
Marketing directorDavid Mayhew
Marketing ManagerCarrie Sherrill
professional technology and Strategy directorBarry Pruett
Business ManagerAmy Knies
associate publisherJim Minatel
project coordinator, coverPatrick Redmond
proofreaderNancy Carrasco
indexerJohnna VanHoose Dinse
cover designerWiley
cover image©iStock .com/llandrea
acknowledgMentS
FirSt i would like to thank my friend, Kenan Sevindik, for joining me on this journey. Special thanks go to the creators of the Spring Framework, Rod Johnson and Jürgen Höller, for crowning our book with their Forewords. Without their ideas and inspirations that ignited all of us, this book wouldn’t even exist.
I also would like to thank our associate publisher, Jim Minatel; project editor, Charlotte Kughen; technical editors, Chád Darby and Krishna Srinivasan; copy editor, Kim Cofer; and production edi-tor, Rebecca Anderson. These people accompanied us during the entire writing process and made the book publication possible with their support, suggestions, and reviews.
Last but not the least, I would like to thank my mom, my dad, my Tugçe, and especially my beloved Funda, who gives me her never‐ending support and enthusiasm.
—Mert Çaliskan
FirSt oF all, i would like to thank my wife, Betül, for her endless support while I was writing this book. I also would like to thank my colleague, Muammer Yücel, for his encouragement and motiva-tion. Although this book is a direct result of our extensive experience with the Spring Application Framework, it wouldn’t be what it is without the help and valuable comments of our project editor, Charlotte Kughen; technical editors, Chád Darby and Krishna Srinivasan; copy editor, Kim Cofer; and production editor, Rebecca Anderson.
—Kenan Sevindik
Contents
Forewords xxvii
IntroductIon xxxi
Chapter 1: poJo programming model, lightweight Containers, and inversion of Control 1
POJO Programming Model 2Problems of the Old EJB Programming Model 2Benefits of the POJO Programming Model 7
Lightweight Containers and Inversion of Control (IoC) 8Lightweight Containers 8Inversion of Control (IoC) 9
Dependency Injection 10Setter Injection 11Constructor Injection 11Setter or Constructor Injection 12
Summary 12
Chapter 2: dependenCy inJeCtion with spring 17
Spring IoC Container 18Configuration Metadata 18Configuring and Using the Container 21
Dependency Injection 29Setter Injection 30Constructor Injection 31Circular Dependencies 34Dependency Resolution Process 35Overriding Bean Definitions 36Using the depends‐on Attribute 38Autowiring 39Bean Lookups 43
Spring‐Managed Beans 44Naming Beans 44Bean Instantiation Methods 45Bean Scopes 48Lazy Initialization 51
xviii
COntentS
Life-Cycle Callbacks 52Bean Definition Profiles 54Environment 56
Summary 59
Chapter 3: Building weB appliCations using spring mvC 63
Learning the Features and Benefits of Spring MVC 64Using the Dispatcher Servlet Mechanism 65
Defining the Servlet 66Accessing Servlet Context 67
Creating Your First Spring MVC Application 68Configuring Spring MVC with Annotations 71Handling Forms with JSP 73
Configuring the Form Tag Library 73Understanding the Power of Binding 74Working with Forms 74Using Input Elements 75Entering Dates 76Selecting from a Drop‐Down 77Selecting with Radio Buttons 78Selecting with Checkboxes 78Adding Labels 78Placing Buttons 79Styling 79
exploiting the Power of Annotations 84@Controller 84@RequestMapping 84@ModelAttribute 84@PathVariable 85@ControllerAdvice 85@InitBinder 85@ExceptionHandler 85
Validating User Input 86Uploading Files 90Handling exceptions 93Implementing Internationalization (i18n) 95Using themes 97Summary 100
xix
COntentS
Chapter 4: JdBC data aCCess with spring 103
Problems with Using Vanilla JDBC 104Introducing Spring’s JDBC Support 105
Managing JDBC Connections 105Embedded DB Support 108Using a Connection‐Pooled DataSource 110Initializing DB 111
Configuring and Using Spring’s JDBC Support 112Performing Data Access Operations with Spring 114
Running Queries 114Queries with Named Parameters 117Writing Queries Using the IN Clause 118Using PreparedStatements within JdbcTemplate 119Inserting, Updating, and Deleting Records 121Calling Stored Procedures and Stored Functions 124Performing Batch Operations 126Handling BLOB and CLOB Objects 126Accessing Vendor‐Specific JDBC Methods 127Executing DDL Operations 127
Modeling JDBC Operations as Java Objects 128Encapsulating SQL Query Executions 128Encapsulating SQL DML Operations 130Encapsulating Stored Procedure Executions 131
exception Handling and error Code translation 132Common Data Access Exception Hierarchy 132Automatic Handling and Translation of SQLException 132
Summary 133
Chapter 5: data aCCess with Jpa using spring 137
Brief Introduction to ORM and JPA 138Paradigm Mismatch 138Building Blocks of an ORM Framework 139What JPA Offers 139Mapping the Object Model to the Relational Model 140
Defining Entities 140Mapping Attributes to Columns 141Creating Associations between Objects 142Mapping Java Types to SQL Types 145
xx
COntentS
Configuring and Using JPA 147Performing CRUD Operations on Objects 150Querying with Object Query Language 155
Spring’s JPA Support 156Setting Up JPA in Spring Container 156Implementing DAOs Based on Plain JPA 161Handling and Translating Exceptions 166Further JPA Configuration in Spring Environment 167
JpaDialect 168JpaVendorAdapter 168JPA and Load Time Weaving 169Dealing with Multiple Persistence Units 170
Summary 171
Chapter 6: managing transaCtions with spring 175
Understanding transaction Management 176Spring’s transaction Abstraction Model 180
Local versus Global Transactions 182PlatformTransactionManager Implementations 182Advantages of Spring’s Abstract Transaction Model 183
Declarative transaction Management with Spring 183Isolating the Service Layer from Data Access Technology Details 186Customizing Default Transactional Behavior 189Using @Transactional on the Class Level 190Understanding Transaction Propagation Rules 191
Propagation REQUIRED 191Propagation REQUIRES_NEW 192Propagation NESTED 192Propagation SUPPORTS 192Propagation NOT_SUPPORTED 192Propagation NEVER 193Propagation MANDATORY 193
Using <tx:advice> for Declarative Transaction Management 195Programmatic transaction Management with Spring 197
Using the PlatformTransactionManager Approach 201executing Custom Logic Before or After transactions 203
Advising Transactional Operations 203Executing Logic after Transactions Using TransactionSynchronization 204
Summary 205
xxi
COntentS
Chapter 7: test‐driven development with spring 209
Configuring and Caching ApplicationContext 210Using XML‐ and Java‐Based Context Configuration in Tests 210Configuring Context with ApplicationContextInitializer 214Inheriting Context Configuration 214ApplicationContext Caching 216
Injecting Dependencies of test Fixtures 217Using transaction Management in tests 219testing Web Applications 222
Context Hierarchies in Tests 225Testing Request‐ and Session‐Scoped Beans 225Testing Spring MVC Projects 227
Testing Controllers 227Testing Form Submit 228Testing Exception Handlers 230Printing Mock Request and Response 231
Using Mock Objects and Other Utilities for testing 231Spring Provided Mock Objects for Testing 231Other Utilities and Test Annotations 232
Summary 233
Chapter 8: aspeCt‐oriented programming with spring 237
Getting Started with AOP with Spring 239Becoming Familiar with types of Advices 243
Before 245After Returning 245After Throwing 245After (Finally) 246Around 247
Defining Point‐Cut Designators 248The Type Signature Expressions 248The Method Signature Expressions 249Other Alternative Point‐Cut Designators 249
Wildcards 250Capitalizing on the Power of Annotations 250
@Before 250@Pointcut 251@After 252@AfterReturning 252
xxii
COntentS
@AfterThrowing 252@Aspect 253@Around 253@DeclareParents 254
Blending AspectJ with Spring 255Configuring Spring AOP with Annotations 259Summary 259
Chapter 9: spring expression language 263
Configuring Applications with SpeL 264Creating a Parser 267Invoking Methods 270
Calling Constructors 272Calling Static Methods 272
Working with Variables and Functions 273#root 273#this 274Accessing System Properties and Environment 274Inline Lists 274Registering Functions 274
Understanding SpeL Operators 275Relational Operators 276Arithmetic Operators 276Logical Operators 276Conditional Operators 277Regular Expression Operator 278Safe Navigation Operator 278Collection Selection and Projection 279Selecting the First and Last Element of a Collection 280
Using Utilities in SpeL 280Accessing Spring Beans 280<spring:eval> 281Expressions in Caching 281
Summary 281
Chapter 10: CaChing 285
Building Your First Caching Application 286Configuring the Cache Manager with a Different Name 289Configuring the Caching Abstraction with Annotations 289
Working with Cache Annotations 290
xxiii
COntentS
@Cacheable 290Key Generator 291Conditional Caching 291
@CacheEvict 292@CachePut 292@Caching 293
Implementing Cache Managers 293SimpleCacheManager 293NoOpCacheManager 294ConcurrentMapCacheManager 294CompositeCacheManager 294
Casting Your SpeL on Caches 295Initializing Your Caches Programmatically 296Finding Alternative Cache Providers 298
Ehcache 299Guava 302Hazelcast 302
Summary 303
Chapter 11: restful weB serviCes with spring 305
Creating Your First ReSt Web Service 306Returning Different HttP Status Codes from ReSt Web Service 318Learning an Annotation‐Based Configuration Alternative 318Using ReSt Web Services with XML 320Using the exception Handling Mechanism 322Unit testing ReStful Services 326Summary 328
Chapter 12: seCuring weB appliCations with spring seCurity 331
Why Spring Security? 332Features of Spring Security 333Configuring and Using Spring Security 334Understanding the Fundamental Building Blocks of Spring Security 340Authenticating Users 341
Unsuccessful Login Flow 342Successful Login Flow 342Anonymous Authentication 344
xxiv
COntentS
Customizing the Login Page 344Logout Process 346Accessing UserDetails Using JDBC 346Encrypting Passwords 349Remember‐Me Support 350User Session Management 351Basic Authentication 352
Authorizing Web Requests and Service Method Calls 353Authorizing Web Requests 353How Does Authorization Work? 355Expression‐Based Authorization 357Using JSP Security Tags 358
Authorize Tag 359Authenticate Tag 359
Authorizing Service Methods 359Summary 364
Chapter 13: next stop: spring 4.0 369
Keeping Up with the Latest: Java 8 and Java ee7 Support 370Lambda Expressions 370
Method References 373Bean Validation Integration 374JSR 310: Date Time Value Type Support 374
Configuring Injection with Conditional Dependency 374Ordering the elements of Autowired Collections 377Repeating Annotations 379Introducing new Annotations 381
Documenting with @Description 381Using the @RestController Annotation 382
Summary 382
APPenDIX: SOLUtIOnS tO eXeRCISeS 385
Chapter 1 385Chapter 2 388Chapter 3 393Chapter 4 393Chapter 5 399Chapter 6 403Chapter 7 406Chapter 8 409
xxv
COntentS
Chapter 9 411Chapter 10 414Chapter 11 417Chapter 12 420Chapter 13 423
Index 425
Foreword
I have fond memories of Wrox books. The Spring story started 12 years ago from a Wrox book. Before that, I’d contributed chapters to several Wrox books and served as a reviewer on many others.
Some of these memories concern what the imprint has meant to me, but many relate to its phi-losophy and format, a key reason I was excited to become a Wrox author in 2000. The distinctive format offers an effective structure for imparting knowledge, encouraging the author to highlight important points, and promoting systematic explanation. It emphasizes practical code examples—the most valuable tool for teaching programming.
These virtues are evident in Mert Çalıskan’s and Kenan Sevindik’s Beginning Spring. It’s well struc-tured, with plentiful examples that include clear instructions on getting the code running and step‐by‐step explanations.
Spring—like building enterprise Java applications itself—is a broad subject, making it impossible for an introductory book to cover even the core Spring Framework exhaustively. Mert and Kenan have done a good job in selecting what to focus on. The scope of this book is well chosen to get you pro-ductive as a Spring web developer: the core Dependency Injection container; the MVC framework (with a special emphasis on REST); relational data access and transaction management; the use of AOP and Spring EL to customize application behavior; and how Spring 4.0 embraces the important language enhancements in Java 8. Although Spring Security is the only Spring subproject covered, this book provides a solid base on which to build knowledge of the broad Spring ecosystem.
The level of the content is equally well targeted. There’s a judicious mix of important background information (for example, the ACID properties of transactions) and specific detail about how to use Spring to get things done. Although this book assumes no knowledge of Spring, it does not waste time covering programming topics better served in more introductory books.
Although I’m no longer personally involved, I continue to observe Spring’s progress with pleasure. Reading this book serves as a reminder of why Spring remains so relevant. The core concepts have stood up well over the past 12 years: for example, the consistent, lightweight approach to transac-tion management and the central principle of Dependency Injection. When you understand the “Spring way,” you can master additional Spring technologies quickly.
If you’re a Java web developer as yet unfamiliar with Spring, you will find that Spring can make your life much easier, and I recommend this book as a good way to get started with it.
—Rod Johnson