44
INTRODUCTION TO SPRING FRAMEWORK ©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. v Table of Contents CHAPTER 1: INTRODUCTION TO SPRING What is Spring? ............................................................................................ 1-2 Spring IO Platform Projects .......................................................................... 1-3 Overview of the Spring Framework............................................................... 1-4 Spring Philosophies ...................................................................................... 1-6 Spring Documentation .................................................................................. 1-7 CHAPTER 2: A FIRST LOOK AT SPRING A Simple Example ........................................................................................ 2-2 Wiring Beans ................................................................................................ 2-5 Configuring a Properties File ........................................................................ 2-8 Schema-Based Configuration File .............................................................. 2-10 CHAPTER 3: SPRING BEANS Bean Functionality ........................................................................................ 3-2 Spring Configuration File .............................................................................. 3-3 Spring Beans ................................................................................................ 3-4 Accessing the Spring Container.................................................................... 3-5 Singleton vs. Prototype ................................................................................. 3-6 Bean Naming ................................................................................................ 3-9 Dependency Injection ................................................................................. 3-11 Setter Injection ............................................................................................ 3-12 Constructor Injection ................................................................................... 3-16 CHAPTER 4: THE APPLICATION CONTEXT The ApplicationContext Interface ......................................................... 4-2 Accessing Application Components.............................................................. 4-3 Accessing Resources ................................................................................... 4-5 Internationalization with MessageSource ................................................... 4-9 Application Events ...................................................................................... 4-13 CHAPTER 5: DATA VALIDATION AND CONVERSION The Validator Interface ............................................................................ 5-2 The Errors Interface................................................................................... 5-3 The ValidationUtils Class .................................................................... 5-6 Validator Example......................................................................................... 5-7 Testing the Validator ................................................................................... 5-10 Property Editors .......................................................................................... 5-12 Custom Property Editors ............................................................................. 5-18 CHAPTER 6: ASPECT-ORIENTED PROGRAMMING Aspect-Oriented Programming ..................................................................... 6-2 AOP Concepts .............................................................................................. 6-3 AOP Proxies ................................................................................................. 6-4 The AOP Alliance ......................................................................................... 6-5 Types of Advice ............................................................................................ 6-6 EVALUATION COPY Unauthorized reproduction or distribution is prohibited

Table of Contents - itcourseware.com€¦ · INTRODUCTION TO SPRING FRAMEWORK ©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED. vi AOP Example.....6-7

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

INTRODUCTION TO SPRING FRAMEWORK

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

v

Table of Contents

CHAPTER 1: INTRODUCTION TO SPRING What is Spring? ............................................................................................ 1-2 Spring IO Platform Projects .......................................................................... 1-3 Overview of the Spring Framework............................................................... 1-4 Spring Philosophies ...................................................................................... 1-6 Spring Documentation .................................................................................. 1-7

CHAPTER 2: A FIRST LOOK AT SPRING A Simple Example ........................................................................................ 2-2 Wiring Beans ................................................................................................ 2-5 Configuring a Properties File ........................................................................ 2-8 Schema-Based Configuration File .............................................................. 2-10

CHAPTER 3: SPRING BEANS Bean Functionality ........................................................................................ 3-2 Spring Configuration File .............................................................................. 3-3 Spring Beans ................................................................................................ 3-4 Accessing the Spring Container.................................................................... 3-5 Singleton vs. Prototype................................................................................. 3-6 Bean Naming................................................................................................ 3-9 Dependency Injection ................................................................................. 3-11 Setter Injection............................................................................................ 3-12 Constructor Injection................................................................................... 3-16

CHAPTER 4: THE APPLICATION CONTEXT The ApplicationContext Interface ......................................................... 4-2 Accessing Application Components.............................................................. 4-3 Accessing Resources ................................................................................... 4-5 Internationalization with MessageSource ................................................... 4-9 Application Events ...................................................................................... 4-13

CHAPTER 5: DATA VALIDATION AND CONVERSION The Validator Interface ............................................................................ 5-2 The Errors Interface................................................................................... 5-3 The ValidationUtils Class .................................................................... 5-6 Validator Example......................................................................................... 5-7 Testing the Validator................................................................................... 5-10 Property Editors .......................................................................................... 5-12 Custom Property Editors............................................................................. 5-18

CHAPTER 6: ASPECT-ORIENTED PROGRAMMING Aspect-Oriented Programming ..................................................................... 6-2 AOP Concepts .............................................................................................. 6-3 AOP Proxies ................................................................................................. 6-4 The AOP Alliance ......................................................................................... 6-5 Types of Advice ............................................................................................ 6-6

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

vi

AOP Example ............................................................................................... 6-7 Introductions ............................................................................................... 6-14

CHAPTER 7: USING JDBC WITH SPRING A Simpler Approach...................................................................................... 7-2 The JdbcTemplate Class........................................................................... 7-3 Exception Translation ................................................................................... 7-7 Updating with the JdbcTemplate ............................................................... 7-9 Queries Using the JdbcTemplate ............................................................ 7-13 Mapping Results to Java Objects ............................................................... 7-16

CHAPTER 8: USING HIBERNATE WITH SPRING What is Hibernate? ....................................................................................... 8-2 Hibernate Sessions....................................................................................... 8-3 Configuring Hibernate in Spring.................................................................... 8-4 The HibernateTemplate .......................................................................... 8-6 Sample Class with Annotations .................................................................... 8-7 Sample Class and Mapping File ................................................................... 8-8 Creating and Saving a New Entity ................................................................ 8-9 Locating an Existing Entity.......................................................................... 8-10 Updating an Existing Entity......................................................................... 8-11 Hibernate Query Language......................................................................... 8-12 Executing Queries ...................................................................................... 8-14

CHAPTER 9: SPRING WEB MVC - PART 1 Spring Web MVC.......................................................................................... 9-2 The DispatcherServlet .......................................................................... 9-3 Writing a Controller ....................................................................................... 9-4 A Simple View Page ..................................................................................... 9-6 Configuring the Controller ............................................................................. 9-7 Adding a View Resolver................................................................................ 9-8 Adding a Message Bundle............................................................................ 9-9 Adding Business Classes ........................................................................... 9-11 Adding Test Data ........................................................................................ 9-16 Accessing a Database ................................................................................ 9-18 Adding a Form ............................................................................................ 9-21 Updating the Database ............................................................................... 9-27 Integrating Hibernate .................................................................................. 9-30

CHAPTER 10: SPRING WEB MVC - PART 2 Handler Mappings....................................................................................... 10-2 View Resolution .......................................................................................... 10-4 Chaining View Resolvers............................................................................ 10-7 Controllers .................................................................................................. 10-8 AbstractWizardFormController...................................................... 10-11

APPENDIX A: RESOURCES Resources.....................................................................................................A-2 Spring Annotations Example.........................................................................A-4

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 1: INTRODUCTION TO SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

1-1

Chapter 1: Introduction to Spring

1) What is Spring?........................................................................................................ 1-2

2) Spring IO Platform Projects ................................................................................... 1-3

3) Overview of the Spring Framework....................................................................... 1-4

4) Spring Philosophies.................................................................................................. 1-6

5) Spring Documentation............................................................................................. 1-7

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 1: INTRODUCTION TO SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

1-2

What is Spring?

• The Spring Framework is a leading full-stack Java / Java EE application framework.

• Application frameworks help developers write and "glue" together the various parts of a software project. A full-stack framework includes all the necessary components to assemble a fully working, ready-to-use application.

• Spring provides significant benefits for many projects, increasing development productivity and runtime performance while improving application quality.

• In particular, Spring addresses the issue of dependencies between components.

• Since the initial release of the Spring Framework in 2002, the Spring world has exploded into a huge family of projects. In 2014, the Spring IO platform was released, bringing together the key projects into a cohesive and versioned platform.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 1: INTRODUCTION TO SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

1-3

Spring IO Platform Projects

• Spring Framework

• Spring Cloud

• Spring Data

• Spring Integration

• Spring Batch

• Spring Security

• Spring Social

• Spring Mobile

• Spring for Android

• Spring Web Flow

• Groovy

• Grails

• Spring LDAP

• And others! See: spring.io/projects

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 1: INTRODUCTION TO SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

1-4

Overview of the Spring Framework

• The Spring Framework is organized into seven modules.

DAO ORM MVC

AOP WEB

CONTEXT

CORE

• Core - The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code.

• Context - The Spring context is a configuration file that provides context information to the Spring framework.

• AOP - The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework through its configuration management feature. The Spring AOP module provides declararative transaction management services for objects in any Spring-based application.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 1: INTRODUCTION TO SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

1-5

Overview of the Spring Framework

• DAO - The Spring JDBC Data Access Object abstraction layer offers an unchecked exception hierarchy for managing the exception handling and error messages thrown by JDBC operations. The DAO module simplifies error handling and greatly reduces the amount of "boilerplate" code you need to write, such as opening and closing connections.

• ORM - The Spring framework integrates nicely with several object-relational mapping tools (including Hibernate).

• Web - The Web context module builds on top of the application context module, providing contexts for Web-based applications.

• MVC - The Spring Model-View-Controller framework is a full-featured MVC implementation for building Web applications.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 1: INTRODUCTION TO SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

1-6

Spring Philosophies

• Spring is a technology dedicated to allowing you to build applications using POJOs ("Plain Old Java Objects").

• Programming to an interface rather than an implementation is always a good practice and is definitely encouraged by Spring.

• A central concept of the Spring framework is non-invasiveness, which means that you should not be forced to introduce framework-specific classes into your domain model. Spring (almost) always offers you the choice.

• In general, Spring is not prescriptive. While Spring makes it easy to use good practices, it avoids forcing a particular approach.

• Spring is consistent.

• Spring does not reinvent the wheel.

• "Make the right thing easy to do."

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 1: INTRODUCTION TO SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

1-7

Spring Documentation

• Spring documentation can be found in the docs directory of the Spring distribution. There are two subdirectories, which are described below.

• spring-framework-reference - contains the reference guide in HTML and PDF format

• javadoc-api - contains the JavaDocs for the Spring classes, interfaces, and exceptions

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 1: INTRODUCTION TO SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

1-8

This Page Intentionally Left Blank

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-1

Chapter 2: A First Look at Spring

1) A Simple Example.................................................................................................... 2-2

2) Wiring Beans ............................................................................................................ 2-5

3) Configuring a Properties File ................................................................................. 2-8

4) Schema-Based Configuration File ........................................................................ 2-10

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-2

A Simple Example

• We begin by defining a simple POJO class.

HelloWorld.java

1. package examples.hello; 2. 3. public class HelloWorld { 4. 5. private String greeting; 6. 7. public void sayHello() { 8. System.out.println (greeting); 9. } 10. 11. public void setGreeting(String greeting) { 12. this.greeting = greeting; 13. } 14. }

• The value of the "greeting" property is specified in the beans configuration file. This setting triggers a call to the setGreeting() method in the implementation class.

• This mechanism is referred to as dependency injection.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-3

A Simple Example

hello.xml

1. <?xml version="1.0" encoding="UTF-8"?> 2. <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN 2.0//EN" 3. "http://www.springframework.org/dtd/spring- 4. beans-2.0.dtd"> 5. 6. <beans> 7. <bean id="hello" 8. class="examples.hello.HelloWorld"> 9. 10. <property name="greeting"> 11. <value>Hello Spring World!</value> 12. </property> 13. 14. </bean> 15. </beans>

• Note the XML prolog (line 1), the reference to the Document Type Definition (lines 2-4), and the top-level <beans> element (lines 6 and 15). Although these lines will not always be shown in the course notes, they are always included in the Spring configuration file.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-4

A Simple Example

• The Spring container manages the configuration and life-cycle of beans. There are two interfaces to the Spring container, BeanFactory and ApplicationContext.

ApplicationContext is a sub-interface of BeanFactory.

Most applications (except for those with limited memory) use implementations of ApplicationContext, .

• We begin our examples by using ClassPathXmlApplicationContext, which reads Spring configuration information from an XML file on the classpath.

HelloTest.java

1. package examples.hello; 2. 3. import org.springframework.context. 4. ApplicationContext; 5. import org.springframework.context.support. 6. ClassPathXmlApplicationContext; 7. 8. public class HelloTest { 9. 10. public static void main(String[] args) { 11. ApplicationContext ctx = new 12. ClassPathXmlApplicationContext("hello.xml"); 13. 14. HelloWorld service = (HelloWorld) 15. ctx.getBean("hello"); 16. 17. service.sayHello(); 18. } 19. }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-5

Wiring Beans

• Now we will show an example where one bean depends on another. The process of configuring one bean that depends on another is called "wiring" beans.

• Here is an interface and implementation class to work with the HelloWorld bean.

HelloHelper.java

1. package examples.hello; 1. 2. public interface HelloHelper { 3. public String convertString (String 4. original); 5. }

HelloHelperUpperCase.java

1. package examples.hello; 2. 3. public class HelloHelperUpperCase implements 4. HelloHelper { 5. 6. public String convertString (String 7. original) { 8. 9. return original.toUpperCase(); 10. } 11. }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-6

Wiring Beans

• Now here is a revised version of the HelloWorld bean.

HelloWorld2.java

1. package examples.hello; 2. 3. public class HelloWorld2 { 4. 5. private String greeting; 6. private HelloHelper helper; 7. 8. public void sayHello() { 9. System.out.println 10. (helper.convertString(greeting)); 11. } 12. 13. public void setGreeting(String greeting) { 14. this.greeting = greeting; 15. } 16. 17. public void setHelper(HelloHelper helper) { 18. this.helper = helper; 19. } 20. }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-7

Wiring Beans

• Here is the revised configuration.

hello.xml

1. 2. <bean id="hello2" 3. class="examples.hello.HelloWorld2"> 4. 5. <property name="greeting"> 6. <value>Hello Spring World!</value> 7. </property> 8. 9. <property name="helper"> 10. <ref bean="helloHelper"/> 11. </property> 12. </bean> 13. 14. <bean id="helloHelper" 15. class="examples.hello.HelloHelperUpperCase"/> 16.

• Note the use of the <ref> element to reference another bean by its configured id.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-8

Configuring a Properties File

• Instead of hard-coding the greeting message in the beans configuration file, we will read it from a properties file.

• The PropertyPlaceholderConfigurer pulls values from a properties value and places them into bean configuration entries. The default placeholder syntax follows the JSP expression language style.

${property-name}

hello.xml

1. 2. <bean id="propertyPlaceholderConfigurer" 3. class="org.springframework.beans.factory.config. 4. PropertyPlaceholderConfigurer"> 5. 6. <property name="location"> 7. <value>hello.properties</value> 8. </property> 9. </bean> 10. 11. <bean id="hello2props" 12. class="examples.hello.HelloWorld2"> 13. <property name="greeting"> 14. <value>${hello.message}</value> 15. </property> 16. <property name="helper"> 17. <ref bean="helloHelper"/> 18. </property> 19. </bean> 20.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-9

Configuring a Properties File

• Here is the properties file.

hello.properties

1. hello.message=Hello World from properties file

• Here is the test program.

HelloTest2FromPropFile.java

1. package examples.hello; 2. 3. import org.springframework.context. 4. ApplicationContext; 5. import org.springframework.context.support. 6. ClassPathXmlApplicationContext; 7. 8. public class HelloTest2FromPropFile { 9. 10. public static void main(String[] args) { 11. ApplicationContext ctx = new 12. ClassPathXmlApplicationContext("hello.xml"); 13. 14. HelloWorld service = 15. (HelloWorld) ctx.getBean("hello2props"); 16. 17. service.sayHello(); 18. 19. 20. } 21. }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-10

Schema-Based Configuration File

• Newer versions of Spring configuration files may use a schema rather than a DTD.

• While using the older DTD style is still fully supported, the schema-based configuration files are somewhat easier to read and allow for customization through the use of user-defined configuration tags.

• In the schema-based configuration file, the DTD reference is replaced by special attributes on the top-level <beans> tag (shown below).

hello-schema.xml (excerpt)

1. <?xml version="1.0" encoding="UTF-8"?> 2. 3. <beans xmlns="http://www.springframework.org/schema/beans" 4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5. xmlns:aop="http://www.springframework.org/schema/aop" 6. xmlns:tx="http://www.springframework.org/schema/tx" 7. xsi:schemaLocation= 8. "http://www.springframework.org/schema/beans 9. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd 10. http://www.springframework.org/schema/aop 11. http://www.springframework.org/schema/aop/spring-aop-2.0.xsd 12. http://www.springframework.org/schema/tx 13. http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> 14.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-11

Exercises

1. Add a second method to the HelloWorld class:

public void sayGoodBye();

Revise the Spring configuration file so that the message displayed by the sayGoodBye() method is obtained from the properties file.

Solution: solutions.hello.HelloWorld.java solutions.hello.HelloTest.java

2. Write another class that implements the HelloHelper interface such that the convertString() method removes all spaces from the string. Modify the Spring configuration file so that your class is used as the HelloHelper instead of HelloHelperUpperCase.

Solution: solutions.hello.HelloHelperNoSpaces.java solutions.hello.HelloTest.java

3. Revise your solution to the previous exercise so that the character to be removed can be specified in the Spring configuration file.

Solution: solutions.hello.HelloHelperRemoveChar.java solutions.hello.HelloTest.java

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-12

Exercises

4. Write a class that implements the following interface.

public interface WordTranslator { // This method translates a word if // necessary and returns the replacement // word; if translation is not required, // the word is returned unchanged. public String translate (String word); }

Your class should translate "cat" to "dog," leaving all other words unchanged. Write a test program and test your class as a Spring bean.

Solution: solutions.hello.WordTranslator.java solutions.hello.WordTranslatorImpl.java solutions.hello.WordTranslatorTest.java

5. Revise your solution to the previous exercise so that the target and replacement words are injected through <property> settings in the Spring configuration file.

Solution: solutions.hello.WordTranslatorImpl2.java solutions.hello.WordTranslatorTest2.java

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-13

Exercises

6. Write another class that implements the HelloHelper interface so that the convertString() method splits the string into words and passes each word to the translate() method in your implementation of the WordTranslator interface. Wire the two classes together in the Spring configuration file.

Solution: solutions.hello.HelloHelperTranslate.java solutions.hello.HelloTest.java

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 2: A FIRST LOOK AT SPRING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

2-14

This Page Intentionally Left Blank

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-1

Chapter 6: Aspect-Oriented Programming

1) Aspect-Oriented Programming .............................................................................. 6-2

2) AOP Concepts .......................................................................................................... 6-3

3) AOP Proxies ............................................................................................................. 6-4

4) The AOP Alliance .................................................................................................... 6-5

5) Types of Advice ........................................................................................................ 6-6

6) AOP Example ........................................................................................................... 6-7

7) Introductions .......................................................................................................... 6-14

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-2

Aspect-Oriented Programming

• Aspect-oriented programming (AOP) complements object-oriented programming (OOP) by providing another way to think about programming.

• Developers create systems in response to multiple requirements, which can be classified as core module-level requirements or system-level requirements.

• System-level requirements (e.g., authentication, logging, resource pooling, administration, performance, persistence) tend to be independent from one another and from module-level requirements. System-level requirements also tend to "crosscut" numerous core modules.

• Aspects enable you to handle issues that cut across multiple types and objects. These kinds of issues are often referred to as crosscutting concerns.

• AOP lets you implement crosscutting concerns in a loosely coupled fashion and then combine these implementations to form the final system.

In contrast, OOP creates systems using loosely coupled, modularized implementations of core concerns.

• The first step in AOP development is to decompose the requirements to separate the module-level requirements from crosscutting system-level requirements.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-3

AOP Concepts

• Aspect - A modularization of a crosscutting concern. In Spring, aspects are implemented using regular Java classes.

• Join point - A point during execution of a program. In Spring, a join point represents a method execution.

• Advice - Action taken by an aspect at a particular join point.

• Pointcut - A predicate that matches join points. Advice is associated with a pointcut expression and runs at any join point that matches the pointcut.

• Proxy - An object created by the AOP framework in order to implement the aspect contracts.

• Target object - Object being advised by one or more aspects (also referred to as the advised object). In Spring this will always be a proxied object.

• Introduction - Declaring additional methods or fields for a type (also referred to as inter-type declaration).

• Weaving - Linking aspects with application types or objects to create an advised object. Spring performs weaving at runtime.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-4

AOP Proxies

• Invoking a method on an object

obj.whatever() in the calling code calls whatever() directly on the object

• Invoking a method on a proxy

obj.whatever() in the calling code calls whatever() on the proxy, which calls any interceptors (advice) and calls whatever() on the object

Calling Code

Object

Calling Code

Proxy Object

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-5

The AOP Alliance

• The AOP Alliance is a joint effort among representatives of many open source projects (including Spring) to define a standard set of interfaces for AOP implementations.

• Wherever possible, Spring uses the AOP alliance interfaces rather than defining its own. Therefore, note that some of the examples in this chapter use interfaces from the org.aopalliance.intercept package. To view the JavaDocs for the AOP alliance APIs, see:

http://aopalliance.sourceforge.net/doc

• The interfaces used in this chapter are:

org.aopalliance.intercept.MethodInterceptor

org.aopalliance.intercept.MethodInvocation

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-6

Types of Advice

• Before - Executes before a join point, but does not have the ability to prevent execution flow proceeding to the joint point.

Interface: org.springframework.aop.MethodBeforeAdvice

• After returning - Executes after a join point completes normally.

Interface: org.springframework.aop.AfterReturningAdvice

• After throwing - Executes after a join point throws an exception.

Interface: org.springframework.aop.ThrowsAdvice

• Around - Surrounds a join point and can perform custom behavior before and after the method execution and is also responsible for deciding whether or not to proceed to the join point.

Interface: org.aopalliance.intercept.MethodInterceptor

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-7

AOP Example

• Here is an interface and implementation class.

Loan.java

1. package examples.aop; 2. 3. public interface Loan { 4. 5. public String getName(); 6. public double getAmount(); 7. public double getRate(); 8. public int getYears(); 9. 10. public void setName (String n); 11. public void setAmount(double a); 12. public void setRate (double r); 13. public void setYears (int y); 14. 15. public String toString(); 16. 17. public double computePayment(); 18. public double totalInterest(); 19. public void printAmortizationTable(int months); 20. 21. public void assume(Loan source); 22. }

LoanImpl.java

1. package examples.aop; 2. 3. import java.text.DecimalFormat; 4. 5. public class LoanImpl implements Loan { 6. String name; 7. double amount, rate; 8. int years; 9. 10. double interest[]; 11. double principal[]; 12. double balance[];

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-8

AOP Example

LoanImpl.java (continued)

13. 14. public LoanImpl() { 15. name = "John Doe"; 16. amount = 100000; 17. rate = 7.5; 18. years = 30; 19. 20. interest = new double[years * 12]; 21. principal = new double[years * 12]; 22. balance = new double[years * 12]; 23. } 24. 25. public LoanImpl 26. (String n, double a, double r, int y) { 27. 28. name = n; 29. amount = a; 30. rate = r; 31. years = y; 32. 33. interest = new double[years * 12]; 34. principal = new double[years * 12]; 35. balance = new double[years * 12]; 36. } 37. 38. public void assume(Loan source) { 39. double temp = source.getAmount(); 40. amount = amount + temp; 41. source.setAmount(0.0); 42. } 43. 44. public double computePayment() { 45. double monthlyPayment; 46. double j = rate / (12 * 100); 47. int n = years * 12; 48. monthlyPayment = amount * 49. ( j / (1 - Math.pow ((1 + j), -n))); 50. 51. return monthlyPayment; 52. }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-9

AOP Example

LoanImpl.java (continued)

53. public double totalInterest() { 54. double total = 0.0; 55. amortizeLoan(); 56. for(int i = 0; i < 12 * years; i++) { 57. total += interest[i]; 58. } 59. return total; 60. } 61. 62. public void printAmortizationTable(int months){ 63. amortizeLoan(); 64. System.out.println("MONTH\tINT\tPRIN\tBAL"); 65. DecimalFormat df = 66. new DecimalFormat("#,###.00"); 67. 68. for(int i = 0; i < months; i++){ 69. System.out.print((i + 1) + "\t"); 70. System.out.print(df.format(interest[i]) 71. + "\t"); 72. System.out.print(df.format(principal[i]) 73. + "\t"); 74. System.out.println 75. (df.format(balance[i])); 76. } 77. } 78. 79. private void amortizeLoan() { 80. double owed; 81. owed = amount; 82. double payment = computePayment(); 83. 84. for (int i = 0; i < years * 12; i++) { 85. interest[i] = 86. owed * (rate / (12 * 100)); 87. principal[i] = payment - interest[i]; 88. balance[i] = owed - principal[i]; 89. owed = balance[i]; 90. } 91. } 92. }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-10

AOP Example

• Here is a class that provides "before" and "after returning" advice. Its methods will be called before and after the methods that require logging.

LoggingAdvice.java

1. package examples.aop; 2. 3. import java.lang.reflect.Method; 4. 5. import org.springframework.aop.AfterReturningAdvice; 6. import org.springframework.aop.MethodBeforeAdvice; 7. 8. public class LoggingAdvice implements 9. MethodBeforeAdvice, AfterReturningAdvice { 10. 11. public void before(Method arg0, Object[] arg1, 12. Object arg2) throws Throwable { 13. 14. System.out.println("A Before Message"); 15. } 16. 17. public void afterReturning(Object arg0, 18. Method arg1, Object[] arg2, Object arg3) 19. throws Throwable { 20. 21. System.out.println("An After Message"); 22. } 23. }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-11

AOP Example

• Here is a class that provides "around" advice.

AroundAdvice.java

1. package examples.aop; 2. 3. import org.aopalliance.intercept.MethodInterceptor; 4. import org.aopalliance.intercept.MethodInvocation; 5. 6. public class AroundAdvice implements 7. MethodInterceptor { 8. 9. public Object invoke(MethodInvocation arg0) 10. throws Throwable { 11. 12. System.out.println 13. ("Message from AroundAdvice"); 14. 15. Double value = (Double) arg0.proceed(); 16. return value; 17. } 18. }

• The proceed() method invokes the original method that is receiving the around advice. Note that the advice is allowed to execute before and after the method invocation, and you control the point at which the method invocation proceeds. You can also choose to bypass the original method altogether and provide your own implementation.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-12

AOP Example

• The Spring configuration file specified which advice should be applied to which methods.

aop.xml

1. <bean id="loanBean" class="examples.aop.LoanImpl"/> 2. 3. <bean id="loanBeanProxy" class= 4. "org.springframework.aop.framework.ProxyFactoryBean"> 5. 6. <property name="proxyInterfaces"> 7. <value>examples.aop.Loan</value> 8. </property> 9. 10. <property name="interceptorNames"> 11. <list> 12. <value>myAdvisor</value> 13. </list> 14. </property> 15. <property name="target"> 16. <ref local="loanBean"/> 17. </property> 18. </bean> 19. 20. <bean id="myAdvisor" class= 21. "org.springframework.aop.support.RegexpMethodPointcutAdvisor"> 22. 23. <property name="advice"> 24. <ref local="myAdvice"/> 25. </property> 26. <property name="pattern"> 27. <value>.*</value> 28. </property> 29. </bean> 30. 31. <bean id="myAdvice" 32. class="examples.aop.LoggingAdvice"/> 33. 34. <bean id="aroundAdvice" 35. class="examples.aop.AroundAdvice"/>

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-13

AOP Example

• Here is the test program.

LoanTest.java

1. package examples.loan; 2. 3. // import's not shown 4. 5. public class LoanTest { 6. public static void main(String args[]) { 7. 8. ApplicationContext ctx = new 9. ClassPathXmlApplicationContext("aop.xml"); 10. 11. Loan loanA = 12. (Loan) ctx.getBean("loanBeanProxy"); 13. 14. loanA.printAmortizationTable(10); 15. 16. DecimalFormat df = 17. new DecimalFormat("#,###.00"); 18. 19. System.out.println("Total Interest: " 20. + df.format(loanA.totalInterest())); 21. 22. ((ClassPathXmlApplicationContext) ctx).close(); 23. } 24. }

• Note that the bean acquired through the application context is the proxy, not the LoanImpl object itself.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-14

Introductions

• Introductions enable an aspect to declare that advised objects implement a given interface, and to provide an implementation of that interface on behalf of those objects.

• Here is a class, an interface, and on the next page, an implementation of the interface.

Car.java

1. package examples.aop; 2. 3. public class Car { 4. 5. }

PaintColor.java

1. package examples.aop; 2. 3. public interface PaintColor { 4. 5. public String getColor(); 6. public void setColor (String color); 7. }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-15

Introductions

PaintColorImpl.java

1. package examples.aop; 2. 3. import org.springframework.aop.support. 4. DelegatingIntroductionInterceptor; 5. 6. public class PaintColorImpl 7. extends DelegatingIntroductionInterceptor 8. implements PaintColor { 9. 10. private String color = "Not Set"; 11. 12. public String getColor() { 13. return color; 14. } 15. 16. public void setColor(String color) { 17. this.color = color; 18. } 19. }

• Note that the implementation class extends Spring's DelegatingIntroductionInterceptor class.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-16

Introductions

aop.xml

1. <bean id="car" class="examples.aop.Car" /> 2. 3. <bean id="paintColor" 4. class="examples.aop.PaintColorImpl" /> 5. 6. <bean id="paintColorAdvisor" class= 7. "org.springframework.aop.support.DefaultIntroductionAdvisor"> 8. 9. <constructor-arg> 10. <ref bean="paintColor" /> 11. </constructor-arg> 12. </bean> 13. 14. <bean id="carProxy" class= 15. "org.springframework.aop.framework.ProxyFactoryBean"> 16. 17. <property name="proxyTargetClass"> 18. <value>true</value> 19. </property> 20. 21. <property name="interceptorNames"> 22. <list> 23. <value>paintColorAdvisor</value> 24. </list> 25. </property> 26. 27. <property name="target"> 28. <ref bean="car"/> 29. </property> 30. </bean>

• Note that in this example, the proxy's target is the implementation class rather than the interface.

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-17

Introductions

PaintColorTest.java

1. package examples.aop; 2. 3. import org.springframework.beans.factory.BeanFactory; 4. import org.springframework.context.support. 5. ClassPathXmlApplicationContext; 6. 7. public class PaintColorTest { 8. 9. public static void main(String[] args) { 10. 11. ApplicationContext ctx = new 12. ClassPathXmlApplicationContext("aop.xml"); 13. 14. Car myCar = (Car) factory.getBean("carProxy"); 15. 16. PaintColor carColor = (PaintColor) myCar; 17. 18. System.out.println ("Is Car?: " + 19. (myCar instanceof Car)); 20. 21. System.out.println ("Is PaintColor?: " + 22. (myCar instanceof PaintColor)); 23. 24. System.out.println ("Color: " + 25. carColor.getColor()); 26. 27. System.out.println ("Changing color to blue"); 28. carColor.setColor ("blue"); 29. 30. System.out.println ("Color: " + 31. carColor.getColor()); 32. 33. ((ClassPathXmlApplicationContext) ctx).close(); 34. } 35. }

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-18

Exercises

1. Modify the LoggingAdvice class so that it also implements the ThrowsAdvice interface. Modify the Loan class so that one of its methods can throw an exception. Modify the LoanTest program so that you call a Loan method and cause an exception, so that you can see evidence of your "after throwing" advice.

Solution: solutions.aop.LoggingAdvice solutions.aop.Loan solutions.aop.LoanImpl solutions.aop.LoanTest

2. Write a class that implements the following interface.

public interface StringDisplayer { public void showString(String text); }

Your showString() method can simply take the input parameter and print it on the screen. Write a test program that displays several strings. (Note: You will use these classes again in the next exercise.)

Solution: solutions.aop.StringDisplayer solutions.aop.SomeClass solutions.aop.SomeClassTest

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-19

Exercises

3. Begin with the interface and class you wrote in the previous exercise. We will now use AOP to change the behavior of the class without any modifications to its source code.

Write and configure an advisor that implements "around" advice so that all calls to the showString() method are intercepted. If the string contains any objectionable words, the showString() method should not be invoked, and a warning message should be printed instead. (Hint: You will need to look at the JavaDocs for the org.aopalliance.intercept.MethodInvocation interface.)

The list of objectionable words should be obtained from a file, which should be configured as a Resource and injected into the advisor bean. (Hint: You might want to review the ConfiguredResourceDemo program in the examples.appctx package. There is also a starter file for the advisor available in the starters.aop package).

Solution: solutions.aop.AroundAdvice solutions.aop.AroundAdviceTest

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited

INTRODUCTION TO SPRING FRAMEWORK CHAPTER 6: ASPECT-ORIENTED PROGRAMMING

©2015 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.

6-20

Exercises

4. Write a class representing items found in the classroom (computer, chair, table, projector, whiteboard, etc.). Call the class ClassroomEquipment class and give it a few data items such as description and location.

A new requirement dictates that each piece of equipment have an alphanumeric tracking number for inventory purposes. Write a class that implements the following interface.

public interface Trackable { public String getTrackingNumber(); public void setTrackingNumber(String n); }

This class should also extend the Spring class called DelegatingIntroductionInterceptor. Create appropriate entries in the Spring configuration file so that ClassroomEquipment will implement the Trackable interface. Write a test program to verify that you are able to call methods in the Trackable interface on objects of type ClassroomEquipment.

Solution: solutions.aop.ClassroomEquipment solutions.aop.Trackable solutions.aop.TrackableImpl solutions.aop.TrackableTest

EVALUATION COPY

Unauthorized reproduction or distribution is prohibited