39,59 €
Build mission-critical enterprise applications using Spring Framework and Aspect Oriented Programming
If you are a Java developer who is looking to master Enterprise Java Development using Spring Framework, then this book is ideal for you. Prior understanding of core Java programming and a high-level understanding of Spring Framework is recommended. Having sound knowledge of servlet-based web development in Java and basic Database concepts would be an advantage but not a requirement.
Spring is an open source Java application development framework to build and deploy systems and applications that run on the JVM. It is the industry standard and the most popular framework among Java developers with over two-thirds of developers using it.
Spring Essentials makes learning Spring so much quicker and easier with the help of illustrations and practical examples. Starting from the core concepts of features such as inversion of Control Container and BeanFactory, we move on to a detailed look at aspect-oriented programming. We cover the breadth and depth of Spring MVC, the WebSocket technology, Spring Data, and Spring Security with various authentication and authorization mechanisms.
Packed with real-world examples, you'll get an insight into utilizing the power of Spring Expression Language in your applications for higher maintainability. You'll also develop full-duplex real-time communication channels using WebSocket and integrate Spring with web technologies such as JSF, Struts 2, and Tapestry. At the tail end, you will build a modern SPA using EmberJS at the front end and a Spring MVC-based API at the back end.By the end of the book, you will be able to develop your own dull-fledged applications with Spring.
This book is a practical guide based on logical modules of the whole Spring Framework family, with a start-small approach, increasing in complexity as it progresses. Every chapter is an amalgamation of theory and practical examples, with further discussion on additional features and approaches.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 271
Veröffentlichungsjahr: 2016
Copyright © 2016 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 authors, 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: February 2016
Production reference: 1230216
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-234-9
www.packtpub.com
Authors
Shameer Kunjumohamed
Hamidreza Sattari
Reviewer
Jarosław Krochmalski
Commissioning Editor
Julian Ursell
Acquisition Editors
Larissa Pinto
Pratik Shah
Content Development Editor
Aishwarya Pandere
Technical Editor
Siddhi Rane
Copy Editors
Kevin McGowan
Madhusudan Uchil
Project Coordinator
Nidhi Joshi
Proofreader
Safis Editing
Indexer
Hemangini Bari
Graphics
Kirk D'Penha
Production Coordinator
Shantanu N. Zagade
Cover Work
Shantanu N. Zagade
Shameer Kunjumohamed is a software architect specializing in Java-based enterprise application integrations, SOA, and the cloud. Besides Java, he is well-versed in the Node.js and Microsoft .NET platforms. He is interested in JavaScript MVC frameworks such as EmberJS, AngularJS, and ReactJS.
Shameer has co-authored another book, Spring Web Services 2 Cookbook, Packt Publishing with Hamidreza Sattari, who is the co-author of this book as well.
Based in Dubai, UAE, Shameer has over 15 years of experience in various functional domains. He currently works as a principal applications architect for a major shipping company in Dubai.
I would like to extend my thanks to a number of people who have inspired and influenced me throughout my technical career. The Java, Spring, and Ember communities gave me the knowledge and confidence to write this book. I thank my parents; my wife, Shehida; and my daughters, Shireen, Shahreen, and Safa, who supported me and put up with me when I was busy writing the chapters; it was their precious time I was taking for this book. Special thanks to my friend Hamidreza, who is a great friend and colleague, and to the coordinators and reviewers at Packt Publishing, who made this book a wonderful resource for learning Spring.
Hamidreza Sattari is an IT professional and has worked in several areas of software engineering, from programming to architecture as well as management. He holds a master's degree in software engineering from Herriot Watt University, UK. In recent years, his areas of interest have been software architecture, data science, and machine learning. He co-authored the book Spring Web Services 2 Cookbook, Packt Publishing in 2012. He maintains the blog http://justdeveloped-blog.blogspot.com/.
First, I should thank the members of the open source community, who are far too many to name. I have been able to write this book by using their products, ideas, articles, and blogs. I would like to give special thanks to my friend Shameer P.K. for his significant role in writing this book.
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 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 at the Danish company 7N as an IT architect for Nykredit Bank. You can reach him via Twitter at @jkroch or by e-mail at <[email protected]>.
I would like to say hello to my friends at 7N and Nykredit; keep up the great job!
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 <[email protected]> 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.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
There are a lot of books written about Spring Framework and its subprojects. A multitude of online references are also available. Most of these massive resources discuss Spring in a lot of detail, which makes learning Spring a very time-consuming and sometimes tedious effort. The idea of this book is to allow novice Java developers or architects to master Spring without spending much time and effort and at the same time provide them with a strong foundation on the topic in order to enable them to design high-performance systems that are scalable and easily maintainable.
We have been using Spring Framework and its subprojects for more than a decade to develop enterprise applications in various domains. While the usage of Spring quickly raises the design quality of projects with its smart templates and subframeworks abstracting many error-prone and routine programming tasks, a developer needs a thorough understanding of its concepts, features, best practices, and above all, the Spring programming model in order to utilize Spring to its best.
We have seen Spring used wrongly inside many projects mainly because the developer either didn't understand the right use of a particular Spring component or didn't bother to follow the design approach Spring suggests for that component. Often, developers didn't appear to have the right knowledge of Spring Framework; when asked, their complaint mostly was the uphill task of learning such a vast framework from huge documentation. Most of this category of developers find Spring a mammoth framework that is difficult to learn, which is not really true.
Spring, if the basics are understood correctly, is very easy to conquer further. A developer needs to understand the Spring style of programming and architecting applications, and the result will be a piece of art. The design will look simple, pretty straightforward, and easily understandable, which is very important for the evolution of applications in the long run. This book is an attempt to fill that gap and provide a very solid foundation in Spring, its concepts, design styles, and best practices, in a very quick and easy way.
This book tries to engage the reader by providing the feeling of developing a realistic, modern enterprise application using Spring and its necessary features while giving him or her a solid understanding of its concepts, benefits, and usage with real-life examples. It covers the most important concepts and features of Spring Framework and a few of its critical subprojects that are necessary for building modern web applications.
The goal of Spring is to simplify enterprise application development. We hope this book simplifies mastering Spring so that developers can build smarter systems that make the world a better place.
Chapter 1, Getting Started with Spring Core, introduces the core Spring Framework, including its core concepts, such as POJO-based programming, Dependency Injection, and Aspect Oriented Programming, to the reader. It further explains the Spring IoC container, bean configurations, Spring Expression Language (SpEL), resource management, and bean definition profiles, all which become the foundation for the advanced topics.
Chapter 2, Building the Web Layer with Spring Web MVC, gives in-depth coverage of the Spring MVC web framework with its features and various different ways of configuring and tuning web applications using Spring. The chapter covers the building of both view-based web applications and REST APIs with many available options, including asynchronous request processing.
Chapter 3, Accessing Data with Spring, discusses the different data-access and persistence mechanisms that Spring offers, including the Spring Data family of projects, such as Spring Data JPA and Spring Data Mongo. This chapter enables the reader to design an elegant data layer for his or her Spring application, delegating all the heavylifting to Spring.
Chapter 4, Understanding WebSocket, discusses the WebSocket technology, which is gaining wider usage inside modern web applications, where low latency and high frequency of communication are critical. This chapter explains how to create a WebSocket application and broadcast a message to all subscribed clients as well as send a message to a specific client, and shows how a broker-based messaging system works with STOMP over WebSocket. It also shows how Spring's WebSocket fallback option can tackle browser incompatibility.
Chapter 5, Securing Your Applications, teaches the reader how to secure his or her Spring applications. It starts with authentication and explains Spring flexibility on authorization. You learn how to integrate your existing authentication framework with Spring. On authorization, it shows how to use Spring EL expressions for web, method, and domain object authorization. It also explains the OAuth 2.0 Authorization Framework and how to allow third-party limited access to user's protected resources on a server without sharing user's username and password.
Chapter 6, Building a Single-Page Spring Application, demonstrates how Spring can be used as the API server for modern single-page applications (SPAs) with an example of an Ember JS application. At first, it introduces the concept of SPAs, and then it explores using Ember JS to build the SPA. Finally, it covers building the backend API that processes requests asynchronously using Spring MVC and implements persistence using Spring Data JPA.
Chapter 7, Integrating with Other Web Frameworks, demonstrates how Spring can be integrated with Java web frameworks such as JSF and Struts so that even web applications not based on Spring MVC can leverage the power of Spring.
In order to execute the sample projects used in this book, you need the following software installed on your computer:
For all chapters, in general, you need the following software:
For Chapter 3, Accessing Data with Spring, you need the following databases:
Additionally, for Chapter 6, Building a Single-Page Spring Application, you need the following software:
If you are a Java developer who is looking to master enterprise Java development using Spring Framework, then this book is ideal for you. A prior understanding of core Java programming and a high-level understanding of Spring Framework is recommended. Having sound knowledge of Servlet-based web development in Java and basic database concepts would be an advantage but not a requirement.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Spring provides mock classes for both client and server sides inside the org.springframework.mock.http and org.springframework.mock.http.client packages."
A block of code is set as follows:
Any command-line input or output is written as follows:
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "STS and Eclipse allow you to run Java web apps from the IDE just by right-clicking Run As and then Run on Server."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/SpringEssentials_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
Spring Framework is the most trusted and widely used application development framework in Enterprise Java. Originally introduced as a simple and lightweight alternative for the complex J2EE, Spring has now grown to become a truly modern application development platform. Spring and its subprojects provide an excellent foundation for end-to-end application development, with features beyond even those provided by the latest Java EE, such as mobile development, social networking, and big data, besides traditional Java web, server-side, or even standalone applications. After more than a decade since its inception, Spring continues to inspire technologies and technologists across the globe.
Although Spring simplifies Java development drastically, software developers and architects are still required to gain a thorough understanding of its core concepts and features in order to deduce the best use of the Spring family. The simplicity Spring offers to otherwise complex Java development is the result of smart abstractions that it provides in the form of excellent APIs and modules. Spring components relieve the developer of all the technical complexity and heavy lifting of common technical and infrastructure plumbing tasks. As the official Spring documentation says, Spring provides comprehensive infrastructure support so that you can focus on your application.
This book is an attempt to make your Spring learning even easier and a more enjoyable experience.
This chapter gives you a solid foundation of the core Spring Framework, guiding you through its core concepts, components, and modules accompanied by relevant sample code snippets that illustrate the best and most practical usage of each feature in order to solve your everyday programming problems.
In this chapter, we will cover the following topics:
Spring covers a wide variety of technological aspects handled by applications of different types, ranging from a simple standalone Java application up to the most complex, mission critical distributed enterprise systems you can imagine. Unlike most other open source or proprietary frameworks that focus on a specific technology concern such as Web, Messaging, or Remoting, Spring successfully covers almost all the technical aspects of business applications. In most cases, instead of reinventing solutions, Spring utilizes and integrates proven existing frameworks to achieve this end-to-end coverage. Spring is highly modular; hence, it noninvasively allows you to cherry-pick just the modules or features you require in order to become a one-stop shop for all your development needs on JVM.
The whole Spring Framework portfolio is organized into three major elements:
Spring is constantly improving and becoming more and more modular with every new version so that you can use just the required modules.
This book is based on Spring version 4.
The core Spring Framework provides basic infrastructure for Java development on top of its core Inversion of Control (IoC) container. The IoC container is an infrastructure that provides Dependency Injection (DI) for applications. Both the concepts of Dependency Injection and IoC containers are explained in detail later in this chapter. The core Spring Framework is divided into the following modules, providing a range of services:
Module
Summary
Core container
Provides the IoC and Dependency Injection features.
AOP and instrumentation
Provides AOP Alliance compliant features for weaving cross-cutting concerns in Spring applications.
Messaging
Provides messaging abstraction over the Spring Integration project for messaging-based applications.
Data access/integration
The data-access/integration layer consists of JDBC, ORM, OXM, JMS, and transaction modules.
Web
Web technology abstraction over Spring MVC, web socket, and portlet APIs.
Test
Unit testing and integration testing support with JUnit and TestNG frameworks.
STS is an Eclipse-based IDE (short forIntegrated Development Environment) for Spring development. You can download the pre-bundled STS from http://spring.io/tools/sts/all or update your existing Eclipse installation from the update site found at the same location. STS provides various high-productivity features for Spring development. In fact, a Java developer can use any IDE of their choice. Almost all the Java IDEs support Spring development, and most of them have got plugins available for Spring.
Spring has many subprojects that solve various application infrastructure needs. From configuration to security, web apps to big data, productivity to enterprise application integration (EAI), whatever your technical pain point be, you will find a Spring project to help you in your application development. Spring projects are located at http://spring.io/projects.
Some notable projects you may find useful right away are Spring Data (JPA, Mongo, Redis, and so on), Spring Security, Spring Web Services, Spring Integration, Spring for Android, and Spring Boot.
The design of Spring Framework is motivated by a set of design patterns and best practices that have evolved in the industry to address the complexity of Object Oriented Programming, including:
Spring implements established design principles and patterns into its elegant components and promotes their use as the default design approach in applications built using Spring. This noninvasive approach lets you engineer robust and highly maintainable systems composed of loosely coupled components and objects written in clean and modular code. Spring Framework components, templates, and libraries realize the goals and concepts explained earlier in the chapter, leaving you to focus on your core business logic.
Spring projects are usually created as Java projects based in Maven, Gradle, or Ivy (which are build automation and dependency management tools). You can easily create a Maven-based Spring project using STS or Eclipse with Spring Tools support. You need to make sure your pom.xml (Maven configuration) file contains, at the minimum, a dependency to spring-context:
Of course, you should add further dependencies to modules such as spring-tx, spring-data-jpa, spring-webmvc, and hibernate, depending on your project type and requirements.
Unless you explicitly specify the repository location, your project works with Maven's central repository. Alternatively, you can point to Spring's official Maven repository (for example, for milestones and snapshots) by specifying it in your pom.xml file:
You can use the Spring release, milestone, and snapshot repositories as required.
If you are using Gradle as your build system, you can declare your dependencies (typically in the build.gradle file) as follows:
If you prefer using the Ivy dependency management tool, then your Spring dependency configuration will look like this:
Dependency Injection is
