Spring Essentials - Shameer Kunjumohamed - E-Book

Spring Essentials E-Book

Shameer Kunjumohamed

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Build mission-critical enterprise applications using Spring Framework and Aspect Oriented Programming

About This Book

  • Step into more advanced features of aspect-oriented programming and API components to build enterprise grade systems
  • Build lightning-fast web applications and REST APIs using Spring MVC and its asynchronous processing capabilities with the view technologies of your choice
  • Explore simplified but powerful data access techniques including JPA (Java Persistence Architecture) repositories and NoSQL data access

Who This Book Is For

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.

What You Will Learn

  • Set up and build standalone and web-based projects using Spring Framework with Maven or Gradle
  • Get familiar with JSP Form processing using Spring and Form Tag Library
  • Develop RESTful API applications for XML and JSON data transfers with non-blocking asynchronous capabilities
  • Explore Spring's comprehensive transaction support for declarative Transaction Management and its integration with Spring's data access abstractions
  • Investigate Spring Data access mechanisms with Spring Data Repositories, a simple and consistent data-access abstraction
  • Construct real-time applications using WebSocket with a SockJS fallback option
  • Understand how to secure your Spring Web and standalone applications using Spring Security declaratively and consistently
  • Get to grips with the end-to-end development of an API-based modern SPA using EmberJS at the front end and SpringMVC at the back end

In Detail

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.

Style and approach

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:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 271

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Spring Essentials
Credits
About the Authors
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Getting Started with Spring Core
The Spring landscape
The Spring Framework modules
Spring Tool Suite (STS)
Spring subprojects
Design concepts behind Spring Framework
Setting up the development environment
Your first Spring application
Inversion of Control explained
Dependency Injection
The Spring IoC container
Configuration metadata
XML-based configuration metadata
Annotation-based configuration metadata
XML-based versus annotation-based configuration
Component stereotype annotations
Java-based configuration metadata
JSR 330 standard annotations
Beans in detail
Bean definition
Instantiating beans
With constructors
With a static factory-method
With an instance factory-method
Injecting bean dependencies
Constructor-based Dependency Injection
Setter-based Dependency Injection
Constructor-based or setter-based DI – which is better?
Cleaner bean definitions with namespace shortcuts
Wiring a List as a dependency
Wiring a Map as a dependency
Autowiring dependencies
Bean scoping
Dependency Injection with scoped beans
Creating a custom scope
Hooking to bean life cycles
Implementing InitializingBean and DisposableBean
Annotating @PostConstruct and @PreDestroy on @Components
The init-method and destroy-method attributes of <bean/>
Container-level default-init-method and default-destroy-method
Working with bean definition profiles
Injecting properties into the Spring environment
Externalizing properties with PropertyPlaceholderConfigurer
Handling resources
Spring Expression Language
SpEL features
SpEL annotation support
The SpEL API
Aspect Oriented Programming
Static and dynamic AOP
AOP concepts and terminology
Spring AOP – definition and configuration styles
XML schema-based AOP
@AspectJ annotation-based AOP
Declaring an @Aspect annotation
Pointcuts
Pointcut designators
Pointcut examples
Advices
The @Around Advice
Accessing Advice parameters
Testing with Spring
Mock objects
Unit and integration testing utilities
Summary
2. Building the Web Layer with Spring Web MVC
Features of Spring MVC
The Model-View-Controller pattern
Your first Spring MVC application
Setting up a Spring MVC application
The project structure of a Spring MVC application
The web.xml file – Springifying the web app
ApplicationContext files in a Spring MVC application
HomeController – @Controller for the home screen
The home.jsp file – the landing screen
Handling incoming requests
The architecture and components of Spring MVC
DispatcherServlet explained
WebApplicationContext – ApplicationContext for the Web
Beans supporting DispatcherServlet and their roles
Controllers in detail
Mapping request URLs with @RequestMapping
URI template patterns with the @PathVariable annotation
Binding parameters with the @RequestParam annotation
Request handler method arguments
Request handler method return types
Setting Model attributes
Building RESTful services for JSON and XML media
Building a RESTful service with RestController
Asynchronous request processing in Spring MVC
Working with views
Resolving views
Resolving JSP views
Binding Model attributes in JSP pages using JSTL
Spring and Spring form tag libraries
Composing a form in JSP
Validating forms
Handling file uploads
Resolving Thymeleaf views
More view technologies
Summary
3. Accessing Data with Spring
Configuring DataSource
Using embedded databases
Handling exceptions in the Spring Data layer
DAO support and @Repository annotation
Spring JDBC abstraction
JdbcTemplate
NamedParameterJdbcTemplate
SimpleJdbc classes
JDBC operations with Sql* classes
Spring Data
Spring Data Commons
Spring Data repository specification
Spring Data JPA
Enabling Spring Data JPA
JpaRepository
Spring Data MongoDB
Enabling Spring Data MongoDB
MongoRepository
Domain objects and entities
Query resolution methods
Using the @Query annotation
Spring Data web support extensions
Auditing with Spring Data
Spring Transaction support
Relevance of Spring Transaction
Spring Transaction fundamentals
Declarative transaction management
Transactional modes – proxy and AspectJ
Defining transactional behavior
Setting rollback rules
Using the @Transactional annotation
Enabling transaction management for @Transactional
Programmatic transaction management
Summary
4. Understanding WebSocket
Creating a simple WebSocket application
STOMP over WebSocket and the fallback option in Spring 4
Broadcasting a message to a single user in a WebSocket application
Summary
5. Securing Your Applications
Authentication
Authorization
The OAuth2 Authorization Framework
Summary
6. Building a Single-Page Spring Application
The motivations behind SPAs
SPAs explained
The architectural benefits of SPAs
SPA frameworks
Introducing Ember.js
The anatomy of an Ember application
Routers
Routes or route handlers
Templates
Components
Models
Controllers
Input helpers
Custom helpers
Initializers
Services
Working with Ember CLI
Setting up Ember CLI
Getting started with Ember CLI commands
The Ember project structure
Working with the POD structure
Understanding the Ember object model
Declaring types (classes) and instances
Accessing and mutating properties
Computed properties
Property observers
Working with collections
Building UI templates using Handlebars
Handlebars helpers
Data binding with input helpers
Using control flow helpers in Handlebars
Using event helpers
Handling routes
Handling UI behavior using components
Building a ToggleButton component step by step
Persisting data with Ember Data
Ember Data architecture
Defining models
Defining model relationships
Building a Taskify application
Building the API server app
Setting up and configuring the project
Defining the model definitions – User and Task
Building API endpoints for the Taskify app
UserController.java
TaskController.java
Building the Taskify Ember app
Setting up Taskify as an Ember CLI project
Setting up Ember Data
Configuring application routes
Building the home screen
Building the user screen
Building a custom helper
Adding action handlers
Building a custom component – modal window
Building userEditModal using {{modal-window}}
Building the task screen
Summary
7. Integrating with Other Web Frameworks
Spring's JSF integration
Spring's Struts integration
Summary
Index

Spring Essentials

Spring Essentials

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

Credits

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

About the Authors

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.

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 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!

www.PacktPub.com

eBooks, discount offers, and more

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.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

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.

What this book covers

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.

What you need for this book

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:

Java version 8 onwardsSpring Framework 4.xApache Maven 3.x.xApache Tomcat 8.x

For Chapter 3, Accessing Data with Spring, you need the following databases:

PostgreSQL 8 onwardsMongoDB 3.x

Additionally, for Chapter 6, Building a Single-Page Spring Application, you need the following software:

Node.js version 4.xBower JS in the latest version

Who this book is for

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.

Conventions

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:

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-framework.version}</version> </dependency> ... </dependencies>

Any command-line input or output is written as follows:

mvn clean package spring-boot:run -Dserver.contextPath=/myapp -Dserver.port=9090

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."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

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.

Customer support

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.

Downloading the example code

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:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Downloading the color images of this book

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.

Errata

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

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.

Questions

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.

Chapter 1. Getting Started with Spring Core

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:

The Spring landscapeSetting up the development environmentYour first Spring applicationCore conceptsThe IoC (Inversion of Control) containerBeans in detailWorking with bean definition profilesHandling resourcesSpEL (Spring Expression Language)Aspect Oriented Programming

The Spring landscape

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 FrameworkSpring Tool SuiteSpring subprojects

Spring is constantly improving and becoming more and more modular with every new version so that you can use just the required modules.

Note

This book is based on Spring version 4.

The Spring Framework modules

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.

Spring Tool Suite (STS)

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 subprojects

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.

Design concepts behind Spring Framework

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:

Simple, noninvasive, and lightweight POJO (Plain Old Java Objects) programming, without having a need for complex application serversLoosely-coupled dependencies, achieved by applying the concepts of program to interfaces and composition over inheritance, which are the underlying design principles of design patterns and frameworksHighly configurable systems composed of objects with externalized Dependency InjectionTemplated abstractions to eliminate repetitive, boilerplate codeDeclarative weaving of cross-cutting aspects without polluting business components

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.

Setting up the development environment

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:

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-framework.version}</version> </dependency> ... </dependencies>

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:

<repositories> <repository> <id>io.spring.repo.maven.milestone</id> <url>http://repo.spring.io/milestone/</url> <snapshots><enabled>false</enabled></snapshots> </repository> </repositories>

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:

dependencies { compile('org.springframework:spring-context') compile('org.springframework:spring-tx') compile('org.hibernate:hibernate-entitymanager') testCompile('junit:junit') }

If you prefer using the Ivy dependency management tool, then your Spring dependency configuration will look like this:

<dependency org="org.springframework" name="spring-core" rev="4.2.0.RC3" conf="compile->runtime"/>

Dependency Injection

Dependency Injection is