Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Getting started with Spring Framework: A Hands-on Guide to Begin Developing Applications Using Spring Framework
Getting started with Spring Framework: A Hands-on Guide to Begin Developing Applications Using Spring Framework
Getting started with Spring Framework: A Hands-on Guide to Begin Developing Applications Using Spring Framework
Ebook552 pages4 hours

Getting started with Spring Framework: A Hands-on Guide to Begin Developing Applications Using Spring Framework

Rating: 4.5 out of 5 stars

4.5/5

()

Read preview

About this ebook

Getting started with Spring Framework is a hands-on guide to begin developing applications using Spring Framework. This book is meant for Java developers with little or no knowledge of Spring Framework. All the examples shown in this book use Spring 3.2.
LanguageEnglish
PublisherBookBaby
Release dateDec 10, 2012
ISBN9781624888359
Getting started with Spring Framework: A Hands-on Guide to Begin Developing Applications Using Spring Framework
Author

Ashish Sarin

Ashish Sarin has over 12 years of experience designing and developing web applications and portals using Java EE and the Portlets APIs. He has authored many articles on portlets and rich internet applications using Liferay, DWR, DOJO, JSF, and Spring Portlet MVC.

Read more from Ashish Sarin

Related to Getting started with Spring Framework

Related ebooks

Information Technology For You

View More

Related articles

Reviews for Getting started with Spring Framework

Rating: 4.5 out of 5 stars
4.5/5

2 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Getting started with Spring Framework - Ashish Sarin

    Summary

    Preface

    You can download the examples described in this book from the following Google Code project: http://code.google.com/p/getting-started-with-spring-framework/

    How to use this book

    Download the examples

    The book comes with many working examples that you can download from the following Google Code project: http://code.google.com/p/getting-started-with-spring-framework/.

    Import the examples into your IDE

    If you see IMPORT: chapter<chapter-number>/ at any point while reading the book, you should import the specified project into your Eclipse IDE or any other IDE that you are using. The source code uses Maven 3.x build tool; therefore, you’ll find a pom.xml file inside each of the projects. A pom.xml file is also provided at the root of the source code distribution, which builds all the projects.

    If you are using Eclipse IDE, execute the following maven command to convert the project into an Eclipse IDE project:

    > mvn clean eclipse:eclipse

    If you are using IntelliJ IDEA, execute the following maven command to convert the project into an IntelliJ IDEA project:

    > mvn clean idea:idea

    Refer to code examples

    You should note that the Project and Source location fields of an example listing specify the project name and the location of the source file where you’ll find the code or configuration shown in the example listing. If the Project and Source location fields are not specified, it means that the code or configuration shown is not being used anywhere in the example projects, and it has been shown purely to help understand a concept.

    Execute the main method of the SpringBankApp or SampleApp class

    Projects that accompany this book represent standalone Java applications. In most of the projects, you’ll find a SpringBankApp or SampleApp class that contains a main method. You can execute the main method of the SpringBankApp or SampleApp class using your IDE. For instance, in case of Eclipse IDE, you can right-click the SpringBankApp or SampleApp class and select Run As --> Java Application option to execute the main method.

    Execute JUnit tests

    If you come across a project that requires you to execute JUnit tests, then execute the JUnit tests using your IDE. In case of Eclipse IDE, you can right-click the JUnit test class and select Run As --> JUnit Test option to execute the tests contained in the JUnit test class.

    Conventions used in this book

    Italics has been used for emphasizing terms

    Century Gothic has been used for example listings, Java code, configuration details in XML and properties files

    Century Gothic bold has been used in example listings to highlight important parts of the code or configuration

    Bold has been used for project names, file names and file paths

    [[-- Anything inside angled brackets like this highlights an important point or concept -- ]]

    Software requirements

    >> Eclipse IDE (http://www.eclipse.org/downloads/) or any other IDE for Java

    >> Java SE 6 or later (http://www.oracle.com/technetwork/java/javase/downloads/index.html)

    >> MySQL database for executing sample projects of Chapter 6 and 7 (http://dev.mysql.com/downloads/mysql/)

    >> HeidiSQL (http://www.heidisql.com/) or any other MySQL database client

    >> Maven 3.x (http://maven.apache.org/download.html)

    Feedback and questions

    You can post your feedback and questions to the authors in the following Google Groups forum: https://groups.google.com/forum/#!forum/getting-started-with-spring-framework

    About the authors

    Ashish Sarin is a Sun Certified Enterprise Architect with more than 13 years of experience in architecting applications. He is the author of Spring Roo 1.1 Cookbook (by Packt Publishing) and Portlets in Action (by Manning Publications)

    J Sharma is a freelance Java developer with extensive experience in developing Spring applications.

    Chapter 1 - Spring Framework basics

    1-1 Introduction

    In the traditional Java enterprise application development efforts, it was a developer’s responsibility to create well-structured, maintainable and easily testable applications. The developers used myriad design patterns to address these non-business requirements of an application. This not only led to low developer productivity, but also adversely affected the quality of developed applications.

    Spring Framework (or ‘Spring’ in short) is an open source application framework from SpringSource (http://www.springsource.org) that simplifies developing Java enterprise applications. It provides the infrastructure for developing well-structured, maintainable and easily testable applications. When using Spring Framework, a developer only needs to focus on writing the business logic of the application, resulting in improved developer productivity. You can use Spring Framework to develop standalone Java applications, web applications, applets, or any other type of Java application.

    This chapter starts off with an introduction to Spring Framework modules and its benefits. At the heart of Spring Framework is its Inversion of Control (IoC) container, which provides dependency injection (DI) feature. This chapter introduces Spring’s DI feature and IoC container, and shows how to develop a standalone Java application using Spring. Towards the end of this chapter, we’ll look at some of the SpringSource’s projects that use Spring Framework as their foundation. This chapter will set the stage for the remaining chapters that delve deeper into the Spring Framework.

    1-2 Spring Framework modules

    Spring Framework consists of multiple modules that are grouped based on the application development features they address. The following table describes the different module groups in Spring Framework:

    The above table shows that Spring covers every aspect of enterprise application development; you can use Spring for developing web applications, accessing databases, managing transactions, creating unit and integration tests, and so on. The Spring Framework modules are designed in such a way that you only need to include the modules that your application needs. For instance, to use Spring’s DI feature in your application, you only need to include the modules grouped under Core container. As you progress through this book, you’ll find details of some of the modules that are part of Spring, and examples that show how they are used in developing applications.

    The following figure shows the inter-dependencies of different modules of Spring:

    Figure 1-1 – Spring modules inter-dependencies

    You can infer from the above figure that the modules contained in the Core container group are central to the Spring Framework, and other modules depend on it. Equally important are the modules contained in the AOP and instrumentation group because they provide AOP features to other modules in the Spring Framework.

    Now, that you have some basic idea about the areas of application development covered by Spring, let’s look at the benefits that you get from using Spring in developing Java enterprise applications.

    1-3 Why use Spring Framework?

    Spring allows you to develop applications using simple Java objects (also referred to as POJOs or Plain Old Java Objects). Java classes corresponding to POJOs are referred to as POJO classes, which are nothing but Java classes that don’t implement or extend framework-specific interfaces or classes. The enterprise services, like transaction management, security, remote access, and so on, required by these POJOs are transparently provided by Spring. Spring also simplifies interaction with JMS providers, JNDI, MBean servers, email servers, databases, and so on, by providing a layer of abstraction that takes care of the boilerplate code.

    Let’s take a quick look at a few examples to better understand the benefits of developing applications using Spring.

    Declarative transaction management

    If you are using Spring for developing transactional applications, you can use Spring’s declarative transaction management support to manage transactions.

    The following example listing shows the FixedDepositService class of MyBank App application:

    Example listing 1-1 – FixedDepositService class

    The FixedDepositService class represents a POJO class which defines methods that allow customers to create a fixed deposit, and to retrieve details of their existing fixed deposits. When a customer chooses the option to create a new fixed deposit, the MyBank App shows the following form:

    Figure 1-2 - Create new Fixed Deposit form

    A customer enters deposit amount, tenure and email id information in the above form and clicks the ‘Save’ button to create a new fixed deposit. Clicking the ‘Save’ button results in invocation of createFixedDeposit method (refer example listing 1-1) of FixedDepositService service. The createFixedDeposit method debits the amount entered by the customer from his bank account, and creates a fixed deposit of the same amount.

    Let’s say that information about the money in a customer’s bank account is stored in BANK_ACCOUNT_DETAILS database table and the fixed deposit details are stored in FIXED_DEPOSIT_DETAILS database table. This means that if a customer creates a fixed deposit of amount x, amount x is subtracted from the BANK_ACCOUNT_DETAILS table, and a new record is inserted in FIXED_DEPOSIT_DETAILS table to reflect the newly created fixed deposit. If BANK_ACCOUNT_DETAILS table is not updated or a new record is not inserted in FIXED_DEPOSIT_DETAILS table, it’ll leave the system in an inconsistent state. This means the createFixedDeposit method must be executed within a transaction.

    The database used by the MyBank App application represents a transactional resource. In the traditional approach to perform a set of database modifications as a single unit of work, you’ll first disable auto-commit mode of JDBC connection, then execute SQL statements, and finally commit (or rollback) the transaction. The following example listing shows how to manage database transactions in the createFixedDeposit method using the traditional approach:

    Example listing 1-2 – Programmatically managing database transaction using JDBC Connection object

    The above example listing shows that the createFixedDeposit method explicitly manages transaction using JDBC Connection object. This approach is suitable for application scenarios in which a single database is involved. Transactions that are resource-specific, like the transaction associated with a JDBC Connection, are referred to as local transactions.

    When multiple transactional resources are involved, JTA (Java Transaction API) is used for managing transactions. For instance, if createFixedDeposit method needs to send a JMS message to a messaging middleware (a transactional resource) in the same transaction in which database (another transactional resource) updates are performed, a JTA transaction manager will be required to manage transactions. JTA transactions are also referred to as global (or distributed) transactions. To use JTA, you fetch UserTransaction object from JNDI and programmatically start and commit (or rollback) transaction.

    As you can see, you can either use JDBC Connection (for managing local transactions) or UserTransaction (for managing global transactions) object to programmatically manage transactions. It is important to note that a local transaction cannot run within a global transaction. This means that if you want database updates in createFixedDeposit method (refer example listing 1-2) to be part of a JTA transaction, you need to modify the createFixedDeposit method to make use of UserTransaction object for transaction management.

    Spring simplifies transaction management by providing a layer of abstraction that gives a consistent approach to managing both local and global transactions. This means that if you write the createFixedDeposit method (refer example listing 1-2) using Spring’s transaction abstraction, you don’t need to modify the method when you switch from local to global transaction management, or vice versa.

    If you are using Spring, you have the option to use declarative transaction management. You can annotate a method with Spring’s @Transactional annotation, and let Spring handle transaction management. For instance, you can specify that the createFixedDeposit method must be executed within a transaction by simply annotating the method with Spring’s @Transactional annotation, as shown in the following example listing:

    Example listing 1-3 – Transactional createFixedDeposit method

    The above example listing shows that the FixedDepositService class doesn’t need to implement any Spring-specific interface or extend from a Spring-specific class to use Spring’s transaction management facility. This shows that Spring is a non-invasive framework because it doesn’t require your application objects to be dependent upon Spring-specific classes or interfaces. Also, you don’t need to directly work with transaction management APIs to manage transactions. The Spring Framework transparently provides transaction management feature to @Transactional annotated createFixedDeposit method.

    Security

    Security is an important aspect of any Java application. You can use Spring Security (http://static.springsource.org/spring-security/site/) to secure your enterprise Java applications. Spring Security is a SpringSource’s project that is built on top of Spring Framework, and provides authentication and authorization features.

    Let’s say that the following 3 user roles have been identified for the MyBank App application: LOAN_CUSTOMER, SAVINGS_ACCOUNT_CUSTOMER and APPLICATION_ADMIN. A customer must be associated with the SAVINGS_ACCOUNT_CUSTOMER or the APPLICATION_ADMIN role to invoke the createFixedDeposit method of FixedDepositService class. If you are using Spring Security, you can easily address this requirement by annotating createFixedDeposit method with Spring Security’s @Secured annotation, as shown in the following example listing:

    Example listing 1-4 – Secured createFixedDeposit method

    If you annotate a method with Spring Security’s @Secured annotation, security feature is applied transparently to the method by the Spring Security framework. The above example listing shows that for implementing method-level security you don’t need to extend or implement Spring-specific classes or interfaces. Also, you don’t need to write security-related code in your business methods.

    JMX (Java Management Extensions)

    Let’s say that the fixed deposit facility of MyBank App application should only be available to customers from 9:00 AM to 6:00 PM everyday. To address this requirement, a variable is added to the FixedDepositService class, which acts as a flag indicating whether the fixed deposit service is active or inactive. The following example listing shows the FixedDepositService class that uses such a flag:

    Example listing 1-5 – FixedDepositService with active variable

    The above example listing shows that a variable named active is added to the FixedDepositService class. If the value of the active variable is true, the getFixedDepositDetails and createFixedDeposit methods work as expected. If the value of the active variable is false, the getFixedDepositDetails and createFixedDeposit methods throw an exception indicating that the fixed deposit service is currently inactive. The activateService and deactivateService methods set the value of active variable to true and false, respectively.

    Now, who calls the activateService and deactivateService methods? Let’s say a separate scheduler application, Bank App Scheduler, runs at 9:00 AM and 6:00 PM to execute activateService and deactivateService methods, respectively. The Bank App Scheduler uses JMX (Java Management Extensions) API to remotely interact with FixedDepositService instance.

    As Bank App Scheduler uses JMX to change the value of the active variable of the FixedDepositService instance, you need to register the FixedDepositService instance as a managed bean (or MBean) with an MBean server, and expose FixedDepositService’s activateService and deactivateService methods as JMX operations. In Spring, you register instances of a class with the MBean server by annotating the class with Spring’s @ManagedResource annotation, and expose the methods of the class as JMX operations using Spring’s @ManagedOperation annotation.

    The following example listing shows how to use the @ManagedResource and @ManagedOperation annotations to register instances of the FixedDepositService class with the MBean server, and to expose activateService and deactivateService methods of the FixedDepositService class as JMX operations:

    Example listing 1-6 – FixedDepositService class that uses Spring’s JMX support

    The above example listing shows that the FixedDepositService class doesn’t make use of JMX API to register its instances with the MBean server and to expose its methods as JMX operations.

    JMS (Java Message Service)

    Let’s say that the customers enrolled with the MyBank App application can submit requests to receive details of all their fixed deposits via email. When a customer submits a request, the FixedDepositService sends the request to a JMS messaging middleware (like ActiveMQ), which saves the request details into a database. Spring simplifies interaction with JMS providers by providing a layer of abstraction. The following example listing shows how FixedDepositService class sends request details to a JMS provider using Spring’s JmsTemplate:

    Example listing 1-7 – FixedDepositService that sends JMS messages

    The above example listing shows that the FixedDepositService defines a variable of type JmsTemplate, and is annotated with Spring’s @Autowired annotation. For now, you can assume that the @Autowired annotation provides access to a JmsTemplate instance. The JmsTemplate instance knows about the JMS destination to which the JMS message is to be sent. How the JmsTemplate is configured is described in detail in chapter 7. The submitRequest method invokes JmsTemplate’s convertAndSend method to send request details (represented by Request argument of submitRequest method) as a JMS message to the JMS provider.

    Once again, the above example listing shows that if you are using Spring Framework to send messages to JMS providers, then you don’t need to directly deal with JMS API classes and interfaces.

    Caching

    It’s common to use caching solutions to improve the performance of an application. MyBank App application uses a caching product to improve the performance of read operations for fixed deposit details. Spring Framework simplifies interacting with caching solutions by abstracting caching-related logic.

    The following example listing shows how the FixedDepositService’s getFixedDepositDetails method class uses Spring’s cache abstraction feature to cache fixed deposit details:

    Example listing 1-8 – FixedDepositService that caches fixed deposit details

    In the above example listing, Spring’s @Cacheable annotation indicates that the fixed deposit details returned by the getFixedDepositDetails method are cached. If the getFixedDepositDetails method is invoked with the same argument value(s), the getFixedDepositDetails method is not executed, and the fixed deposit details are returned from the cache. This shows that if you are using Spring Framework you don’t need to write caching-related logic in your classes.

    In this section, we saw that Spring Framework simplifies developing enterprise applications by transparently providing services to POJOs, thereby shielding developers from lower level API details. Spring also provides easy integration with standard frameworks, like Hibernate, iBATIS, Quartz, JSF, Struts, EJB, and so on, which makes Spring an ideal choice for enterprise application development.

    Let’s now take a look at DI feature and IoC container of Spring Framework.

    1-4 DI and Spring IoC container

    In the traditional approach to application development, developers used design patterns like Factory, Abstract Factory, Builder, Composite, Service Locator, and so on, to put together the objects that form the application. If you are using Spring, the responsibility to create, configure and assemble application objects is with Spring; you don’t need to implement design patterns to compose your application from objects.

    Let’s now look at what DI is, and the role played by the Spring IoC container.

    [[-- In this book, I’ve used the terms Spring IoC container, Spring container and IoC container interchangeably. --]]

    Dependency Injection (DI)

    A Java application is composed of objects that interact with each other to provide application behavior. The other application objects with which an object interacts are referred to as its dependencies. DI is a mechanism in which dependent objects specify their dependencies, and these dependencies are injected into the dependent objects when the dependent objects are created.

    In this section, we’ll see how dependencies are specified in Spring-based applications, and how dependencies are created and injected into dependent objects by the Spring IoC container.

    To use Spring’s DI feature in your application, you need to follow these steps:

    >> identify application objects and their dependencies

    >> create POJO classes corresponding to the identified application objects

    >> create configuration metadata that depicts application objects and their dependencies

    >> create an instance of Spring IoC container and pass the configuration metadata to it

    >> access application objects from the Spring IoC container instance

    Let’s now look at above mentioned steps in the context of MyBank App application.

    Identifying application objects and their dependencies

    We discussed earlier that the MyBank App shows a ‘Create new Fixed Deposit’ form (refer figure 1-2) to its users for creating a fixed deposit. The following sequence diagram shows the application objects (and their interaction) that come into picture when the user submits the ‘Create new Fixed Deposit’ form:

    Figure 1-3 – MyBank App’s application objects and their dependencies

    In the above diagram, the FixedDepositController represents a web controller that receives the request when the ‘Create new Fixed Deposit’ form is submitted. The fixed deposit details are contained in the FixedDepositDetails object. The FixedDepositController invokes the createFixedDeposit method of FixedDepositService (a service layer object). Then, FixedDepositService invokes FixedDepositDao object (a data access object) to save the fixed deposit details in the application’s data store. So, we can interpret from the above diagram that FixedDepositService is a dependency of FixedDepositController object, and FixedDepositDao is a dependency of FixedDepositService object.

    IMPORT: chapter 1/ch01-springbankapp-xml (This project shows how to create a simple Spring application. To run the application, execute the main method of the SpringBankApp class of this project)

    Creating POJO classes corresponding to identified application objects

    Once you have identified objects that compose your application, the next step is to create POJO classes corresponding to these objects. POJO classes corresponding to the FixedDepositController, FixedDepositService and FixedDepositDao application objects are available in ch01-springbankapp-xml project located in chapter 1 directory of the source code

    Enjoying the preview?
    Page 1 of 1