Spring_Framework_Overview_Part2

Page 1

Spring Framework Overview (Part 2) - Aspect Oriented Programming (AOP) A quick overview to understand Spring Framework

Written by: Alan Choy Principal Consultant, eIT Consulting Inc.

http://www.eitconsulting.ca Email: info@eitconsulting.ca

1


INTRODUCTION Java as a language provides a wealth of functionalities and components for application development. The Enterprise Edition of Java (i.e. Java EE) took a step further to define many specifications or “standard”, in an attempt to provide the platform for developing enterprise applications. However, more evolvements have happened in the last few years in the industry, and it became more and more apparent that a lightweight architecture of framework is very desirable to enhance reusability, testability and productivity, especially in light of other waves of development process and methodology changes, such as Agile. Among all the lightweight containers, Spring framework stands out as the most popular and the most widely accepted framework for enterprise application development, with good reasons. There are significant quantity of books and materials about Spring framework available today, but I found most of them are either too simple, which hardly demonstrates the power of Spring, or too complicated, which is too tedious to grasp the main idea for someone who is new to the topic. In this series of Spring framework overview articles, I attempt to provide the optimal details of important concepts, plus adequate complexity of code examples to show what Spring framework is really about. In the first installment of the series of articles, I have introduced the core technologies and concepts of Spring framework, namely IoC (Inversion of Control), DI (Dependency Injection) and Autowiring. In this second installment, I am going to introduce Aspect Oriented Programming (AOP), which is a complement of Object Oriented Programming (OOP) as another way of structuring application codes, and also how AOP was integrated into Spring framework. As usual, code examples will be given to aid illustration using Plain Old Java Object (POJO). In the subsequent installments of this series, I’m going to discuss other very useful components of Spring framework, which includes Spring MVC (Mode-View-Controller) and Spring transaction management support. Please stay tuned.

ABOUT THE AUTHOR Alan Choy is the Principal Consultant of eIT Consulting Inc., which specialized in providing professional services and solution to enterprise application development and maintenance. Alan has held this position since October 2005. Alan has over 11 years of experience in enterprise application development, in multiple international companies, including Ericsson Research Canada, Motorola (Canada) Inc., CGI Group Inc. and Telus Corporation. In the past few years Alan has focused on Java and J2EE platform, with vast experience in many open source technologies such as Spring framework, AOP and Hibernate.

2


AOP CONCEPTS In order to be able to understand AOP, it is vital to first understand the AOP terminologies, which unfortunately is not particularly intuitive: Cross-Cutting concerns: While most classes in OO model would perform some specific primary functions (e.g. data access), they often share common secondary requirements (e.g. logging) with other classes. In such case, the module of a program which implements the secondary requirements are known as cross-cutting concerns, which affects (i.e. crosscut) the other primary concerns. Advice: This is the additional code module (e.g. logging) which would be applied to the existing primary functions. Join Point: This is the point of execution in the application at which the advice will be applied (e.g. when the thread enters a method). Point-cut: A predicate (usually in regular expression) which matches the join point. In general, an advice is associated with a point-cut expression and runs at any join point matched by the point-cut. Aspect: The combination of advice and point-cut are termed as aspect. In Spring AOP, aspects are implemented using regular classes (schema-based approach) or regular classes with @Aspect annotation (@AspectJ approach). Weaving: Linking aspects with the application codes to create an advised object. Weaving can be done at compile time, load time or runtime. In Spring AOP, weaving is performed at runtime. AOP is best explained using an example, and logging is one of the most common crosscutting concerns to illustrate this. Almost all applications somehow need to communicate with some data repositories, and usually via a data access layer, presumably resides in a dao package. Besides implementing the primary functions to query or update the data repositories, most users would want to add some sort of logging before and after a database call. In such case, the code module to perform logging is called advice, the regular expression to represents dao package is called point-cut, and the point of execution before and after a database call is called join point. AOP allows us to dynamically modify our static model to include the code required to fulfill the secondary requirements (i.e. logging) without having to modify the original static model (in fact, we don’t even need to have the original code). Better still, we can often keep this additional code in a single location rather than having to scatter it across the existing model, which we would have to if we were using OO on its own.

3


Generally speaking, there are 5 different types of advices, which are different by the point to execute the advice relatively to the join point: Advice Type Before advice After returning advice After throwing advice After finally advice Around advice

Description Advice that executes before a join point, and it does not have the ability to prevent the flow proceeding to the join point Advice that executes after a join point, which completes normally without an exception Advice that executes after a join point which throws an exception Advice that executes after a join point regardless of the exit state of the join point Advice that executes before and/or after a join point, and it also has the ability to allow or to prevent the flow proceeding to the join point

SPRING AOP AOP in Spring framework has been implemented using pure Java, and hence no need for special compilation process. Contrary to AspectJ, Spring AOP does not provide a complete AOP implementation (e.g. Field Interception is not implemented), but rather providing a tight integration of AOP functionalities into the already powerful framework. Furthermore, Spring AOP is proxy based (will be explained in the next paragraph), which basically forces it to be used together with Spring IoC container. Consider the following diagram:

This diagram illustrates that in Spring AOP, the client calling code does not call the POJO directly, but rather calling the proxy, which in turn delegate the call to the actual target object. In this way, the proxy will be able to invoke all the interceptors or advices that are relevant in the particular method call. Another thing to be aware is that, once the call has finally reached the target object, any method calls that it may make on itself are going to be invoked against the actual target object, and not the proxy.

4


@ASPECTJ SUPPORT @AspectJ refers declaring aspects within regular Java classes using the Java 5 annotation, which also means you need to have Java 5 compiler to work with this. In order to use @AspectJ in Spring, we need to explicitly enabled this in the XML metadata configuration by using the following tag: <aop:aspectj-autoproxy/>

With the @AspectJ support enabled, any bean defined in the application context of the IoC container with @AspectJ annotation, will be detected by Spring framework and configured in Spring AOP. This is best illustrated using an example: Below is the Java code in which an aspect class is defined: package ca.eitconsulting.spring.parttwo; import import import import

org.aspectj.lang.annotation.AfterReturning; org.aspectj.lang.annotation.Aspect; org.aspectj.lang.annotation.Before; org.aspectj.lang.annotation.Pointcut;

@Aspect public class OutputGenerator { @Pointcut("execution(* ca.eitconsulting.spring.parttwo.*.*(..))") public void inParttwo() {} @Before("inParttwo()") public void beforeDebug() { System.out.println("in beforeDebug() advice"); } @AfterReturning(pointcut="inParttwo()", returning="retVal") public void afterDebug(Object retVal) { System.out.println(retVal.getClass().getName() + " - in afterDebug() advice"); } }

The annotation @Aspect at the beginning of the class tells Spring framework this class will be used in Spring AOP. The @Pointcut annotation defines a point-cut to match a join point, and in this case the point-cut means to trigger the advice in any method within the parttwo package. @Before annotation defines a “before advice� beforeDebug(), which will be called by the Spring AOP proxy before reaching the join point. In this case it is associated to point-cut inParttwo(), which means running beforeDebug() method before any method in the parttwo package is executed.

5


@AfterReturning annotation defines an “after returning advice” afterDebug(), which will be called by the Spring AOP proxy if the join point execution is completed normally. Please also note that it is possible to pass a parameter into the advice method, which in this case an object reference is used as an input parameter. As you can recall, Before and AfterReturning are only two of the five kinds of advice which are available. The other includes After (i.e. after finally), AfterThrowing and Around. In general they all follow the same concepts and syntax, and we are not going into depth for each one of them here. Please refer to Spring documentation for more detail description. Below is the Java code of a class which the point-cut defined above will match: package ca.eitconsulting.spring.parttwo; public class MajorLeagueBaseball { private String commissioner; public MajorLeagueBaseball() { System.out.println("MLB Season 2006 using default Constructor!"); } public Object setCommissioner(String commissioner) { this.commissioner = commissioner; System.out.println("MLB Commissioner is " + this.commissioner); return this; } }

MajorLeagueBaseball (yes, you can tell I am a baseball fan!) is a POJO, which defines a default constructor as well as a setter for commissioner attribute. Please note that this setter method does return an object reference, which Spring AOP will use as the input parameter to the “after returning advice” afterDebug() method. Below is the Spring XMLencoding="UTF-8"?> metadata configuration: <?xml version="1.0" <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <bean id="mlb" class="ca.eitconsulting.spring.parttwo.MajorLeagueBaseball"/> <aop:aspectj-autoproxy/> <bean id="out" class="ca.eitconsulting.spring.parttwo.OutputGenerator"/> </beans> Please note that the aop tag is defined in the header, so that it can be used within the XML document. Other than that, the bean definitions are pretty much standard, which we have already covered in part one of this article series.

6


Let us look at the code which triggers the above setup: ApplicationContext context = new ClassPathXmlApplicationContext(configFile); MajorLeagueBaseball mlb = (MajorLeagueBaseball)context.getBean("mlb"); Object obj = mlb.setCommissioner("Bud Selig"); System.out.println("Simple test of Spring AOP");

In this code snippet the Spring IoC container (i.e. application context) reads the configuration file (as shown above), and subsequently calls the setCommissioner() method. Since this method is in parttwo package, which matches the point-cut inParttwo(), it triggers both the beforeDebug() and afterDebug() advices to be executed at the appropriate time. After running the code, the output will be the following: MLB Season 2006 using default Constructor! in beforeDebug() advice MLB Commissioner is Bud Selig ca.eitconsulting.spring.parttwo.MajorLeagueBaseball - in afterDebug() advice Simple test of Spring AOP

At this point you should have a good idea of general AOP concepts, as well as how to use @AspectJ annotation in Spring AOP. In the next section, we will discuss another approach (i.e. Schema-based AOP support) in Spring framework, which defines most of the configurations in XML metadata, rather than in a Java class.

SCHEMA-BASE AOP SUPPORT If for whatever reason you are unable to use Java 5, or simply prefer to use XML configuration instead of using Java code, Spring does support an XML based alternative for Spring AOP. Below is the Java code in which an “aspect� class is defined. Please note that there is no @AspectJ annotation or anything in the source code which indicates this is an aspect class (i.e. the Java class is just POJO). This will be defined later on in the XML metadata configuration: package ca.eitconsulting.spring.parttwo; public class OutputGeneratorSchema { public void beforeDebug() { System.out.println("Schema based beforeDebug() advice"); } public void afterDebug(Object retVal) { System.out.println(retVal.getClass().getName() + " - Schema based afterDebug() advice"); } }

7


Below is the XML configuration to define the point-cut, advice and aspect: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <bean id="mlb" class="ca.eitconsulting.spring.parttwo.MajorLeagueBaseball"/> <bean id="out" class="ca.eitconsulting.spring.parttwo.OutputGeneratorSchema"/> <aop:config> <aop:aspect ref="out"> <aop:pointcut id="inParttwo" expression="execution(* setCommissioner(..))"/> <aop:before pointcut-ref="inParttwo" method="beforeDebug"/> <aop:after-returning pointcut-ref="inParttwo" returning="retVal" method="afterDebug"/> </aop:aspect> </aop:config> </beans>

In this configuration, an aspect is defined, which references OutputGeneratorSchema class as the “aspect” class. In this aspect, a point-cut and two advices (one before and the other after returning) are defined. This has exactly the same functionality as the example given in the previous section. After running the code, the output will be the following: MLB Season 2006 using default Constructor! Schema based beforeDebug() advice MLB Commissioner is Bud Selig ca.eitconsulting.spring.parttwo.MajorLeagueBaseball – Schema based afterDebug() advice Simple test of Spring AOP

At this point, it is worthy to point out that if multiple advices of the same advice type are defined at the same join point, the precedence rule in Spring AOP says the advices will be executed in declaration order, if the advices are defined in the same class. For advices belong to different classes, the order can be controlled by implementing the Ordered interface given in Spring.

8


AOP PROS and CONS AOP technology in general has been available to the public for a few years already, but yet to achieve a widely adoption by the industry. There are obviously pros and cons that result in this phenomenon: Some of the advantages of AOP include: AOP provides a powerful implementation to handle cross-cutting concerns, which dramatically reduces the amount of codes involved. It is naturally to group the AOP point-cuts and advices in a small number of classes, hence enhancing maintainability. Spring AOP and most of other AOP implementations provide a highly flexible environment, which aspects, point-cuts and advices can be defined either at source code level, or in XML metadata. Some of the disadvantages of AOP include: AOP suffers from a lack of tool support and widespread education. This has been improved lately, and we will likely see the popularity of AOP grows with this improvement. If AOP application is not maintained properly, it is easy to introduce unpredictable behavior and widespread error to the application. For example, for operation as simple as changing a method name may have negative effect. Developers need to see the codes and be able to support their application. Some developers get really uncomfortable with AOP as the framework may inject unexpected behavior to their codes without communication. There are security concerns with code weaving, and hence some AOP implementation does not support bytecode weaving, including Spring (Spring only support runtime weavng).

SUMMARY In this article you have learnt about the AOP concept in general, and more specifically the Spring AOP implementations, which include two approaches, namely @AspectJ support and Schema based support. At the end of this article, I have also attempted to list some of the major advantages and disadvantages of using AOP concept in enterprise application development. I personally would anticipate a more widely adoption of AOP as the tool and resource support are getting better and be more easily accessible. As mentioned in the introduction, this article served as the second installment of a series of articles, which covers the major aspects of Spring framework. The next installment will focus Spring MVC (Model-View-Controller). Stay tuned and you won’t be disappointed.

9


RESOURCES Below are some very useful resources for Spring framework: Download the Spring framework binaries, source code and API from the official Spring framework website Introduction to Aspect-Oriented Programming Download the AspectJ binaries and specification from the official AspectJ website Professional Java Development with the Spring Framework By Rod Johnson Published by Wiley; ISBN: 0764574833 Beginning Spring Framework 2 By Thomas Van de Velde, Christian Dupuis and Naveen Balani Published by Wiley; ISBN: 047010161X

FEEDBACK Please let us know whether this tutorial was helpful to you, and how we could make it better. Your comments will be valuable to us, and will be taken into consideration for the subsequent installments of this series of articles. Furthermore, we would also like to hear about other tutorial topics you would like to see covered in the future. For questions about the content of this tutorial, please contact the author, Alan Choy, at alan.choy@eitconsulting.ca.

10


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.