Skip to main content

Using Spring’s AOP Features with Java EE

April 18, 2011

The popular Spring
framework complements and facilitates development on the Java EE
platform by providing a modular, object-based programming model.
Whereas Java EE is OOP (object-oriented programming) based, Spring is
AOP (aspect-oriented programming) based; in fact the AOP framework is
one of the main components of Spring. AOP complements OOP by
providing
an aspect
as the unit of modularity
in addition to the
traditional OOP class. As explained in the Spring doc,
“Aspects enable modularization of concerns such as transaction
management that cut across multiple types and objects. “

A Spring bean may be a
JavaBean, a POJO, or any other object such as an EJB. Spring
implements the Inversion of Control (IoC) principle via dependency
injection. The Spring configuration file is used to specify the
configuration of the Spring beans with the Spring container and the
BeanFactory is used to manage the Spring beans. The BeanFactory
configures, instantiates, and assembles the dependencies among the
objects.

In this article we
shall explore the main AOP-related features in Spring: method
interception and the Spring AOP framework.

Setup

First you will need to
download and install the following:

Add the following JAR
files to the CLASSPATH variable in
C:\Oracle\Middleware\user_projects\domains\base_domain\bin\startWebLogic
batch script. (The Spring JAR files can be added after the Spring
Framework Library has been added to the Spring Web project as
discussed in a later section.)

C:\Spring\lib\aspectjweaver.jar


C:\Spring\lib\aspectjtools.jar


C:\Spring\lib\aspectjrt.jar


C:\Spring\lib\org.aspectj.matcher.jar


C:\Spring\asm-3.3.jar


C:\Spring\cglib-2.2.jar


C:\Spring\aspectj-1.6.10.jar


C:\Users\foo\workspace\libraries\Spring
Framework 2.5.6\spring-framework-2.5.6\dist\spring.jar


C:\Users\foo\workspace\libraries\Spring
Framework
2.5.6\spring-framework-2.5.6\dist\lib\jakarta-commons\commons-logging.jar


C:\Users\foo\workspace\libraries\Spring
Framework 2.5.6\spring-framework-2.5.6\dist\modules\spring-aop.jar;

Creating a
Web Project with Spring Facet

First, we need to
create a Web project in OEPE:



  1. Select Web>Dynamic
    Web Project
    in the New wizard.
  2. In New Dynamic Web
    Project specify a Project name, and configure a target runtime for
    Oracle WebLogic Server 11gR1 Patch Set 2.
  3. Select the Default
    Configuration...
    and click on Next.
  4. Select the default
    Java settings (Source folder as src and output folder as
    build/classes); click on Next.
  5. Specify a Context
    Root and a Content directory.
  6. Select the
    checkbox Generate web.xml deployment descriptor.
  7. Click on Finish.
    A Web project for Spring is created.

Next, add the Spring
project facet to the Web project:



  1. Click on the
    Further Configuration Required link.
  2. In Spring facet
    configuration select Library type as User Library.
  3. Click on Download
    Library
    .
  4. In Download
    Library select the Spring Framework 2.5.6 library from Oracle.
    Click on Next. The library gets added.
  5. Click on OK.
    The Spring facet is installed.
  6. Click on Apply
    and then OK. The Spring Framework 2.5.6 facet is now added to
    the Web project, as shown below.



Figure 1

The Spring bean
definition file applicationContext.xml also gets created. For a
Spring JavaBeans application we shall define the SpringBean factory
configuration in the beanDefinition.xml file and not the
WEB-INF/applicationContext.xml file, which is more suitable for a Web
application. (The applicationContext.xml may be deleted for the
method interception example.)

Right-click on the
project node and select Properties. Select the Java Build
Path
node - the spring.jar should be in the Java Build Path. Now
we're ready to explore these features.

Method
Interception

In this section we
shall discuss the method interceptor mechanism provided by Spring.

Creating a Spring Bean Class

First, we need to
create a Spring bean, which is an object managed, instantiated, and
configured by the framework. We shall create a JavaBean object for
the Spring bean; this object shall implement a magazine catalog with
properties representing the catalog’s journal name, publisher,
edition, title, author. The bean class shall also provide accessor
methods for the bean properties.

We need to create an
interface, CatalogInterface, for the bean class.



  1. Select the project
    node and select File>New.
  2. In the New wizard
    select Java>Interface and click on Next.
  3. Specify a package
    name and a class name and click on Finish. A
    spring.catalog.CatalogInterface interface gets added the src folder.
    The interface CatalogInterface.java is listed below.

package spring.catalog;
public interface CatalogInterface {
public void setJournal(String journal);
public String getJournal();
public void setPublisher(String publisher);
public String getPublisher();
public void setEdition(String edition);
public String getEdition();
public void setTitle(String title);
public String getTitle();
public void setAuthor(String author);
public String getAuthor();
}

Next, add the bean
class Catalog.java, which implements the interface.


  1. Select Java>Class
    in New and click on Next.
  2. In New Java Class,
    specify the package name and the class name and select the interface
    spring.catalog.CatalogInterface. Click on Finish. The
    spring.catalog.Catalog.java class gets added to the Web project.

In the Spring bean
class, provide implementation for the accessor methods for the bean
properties. Also, add a test method getTestMessage() that returns a
String message. The Catalog.java class is listed below.


package spring.catalog;

public class Catalog implements CatalogInterface {

public String journal;
public String publisher;
public String edition;
public String title;
public String author;


public Catalog(){}
public Catalog(String journal, String publisher, String edition,
String title, String author) {

this.journal = journal;
this.publisher = publisher;
this.edition = edition;
this.title = title;
this.author = author;
}

public String getAuthor() {
// TODO Auto-generated method stub
return author;
}

public String getEdition() {
// TODO Auto-generated method stub
return edition;
}

public String getJournal() {
// TODO Auto-generated method stub
return journal;
}

public String getPublisher() {
// TODO Auto-generated method stub
return publisher;
}

public String getTitle() {
// TODO Auto-generated method stub
return title;
}

public void setAuthor(String author) {
// TODO Auto-generated method stub
this.author = author;
}

public void setEdition(String edition) {
// TODO Auto-generated method stub
this.edition = edition;
}

public void setJournal(String journal) {
// TODO Auto-generated method stub
this.journal = journal;
}

public void setPublisher(String publisher) {
// TODO Auto-generated method stub
this.publisher = publisher;
}

public void setTitle(String title) {
// TODO Auto-generated method stub
this.title = title;
}

public String getTestMessage() {
return "Spring Bean Test";
}

}

Creating a Bean Definition File

In this section we
shall create a Spring bean definition file, beanDefinition.xml, to
configure the Spring bean, the Catalog JavaBean, with the Spring
framework. The root element of the beanDefinition.xml is beans
and each of the bean sub-elements represents a Spring bean. We shall
register three beans with the bean configuration file: Catalog
JavaBean, Interceptor bean, and Proxy bean.

To create a bean
configuration file:


  1. Select the project
    node in the Project Explorer and select File>New.
  2. In New select
    Spring>Spring Bean Configuration and click on Next.
  3. In New Spring Bean
    Definition File select the project folder and specify File name
    beanDefinition.xml;
    click on Next.
  4. In Select XSD
    namespaces… select spring-beans-2.5.xsd and click on Next.
  5. Click on Finish. A
    Spring bean definition file beanDefinition.xml gets created.

For each of the beans
to be registered with the Spring framework we need to add a
element. Add a < bracket within the
element and in the pop-up select .



Figure 2

A
element gets added. Next, add an id attribute to the
element. Select the Design tab, right-click on bean, and
select Add Attribute>id.



Figure 3

An id attribute gets
added to the bean element. Specify the id attribute value as
spring-bean. Similarly, add a class attribute to the bean element to
specify the JavaBean class spring.catalog.Catalog. Also add bean
elements for an interceptor bean and a proxy bean. The following
table lists details about the beans you should add.


























bean



id



class



Catalog JavaBean



spring-bean



spring.catalog.Catalog



Interceptor bean



interceptor



spring.catalog.CatalogInterceptor



Proxy bean



proxyBean



org.springframework.aop.framework.ProxyFactoryBean


The bean definition
file with the beans added is shown in the Design view.



Figure 4

Next, we shall add the
following properties to the bean with id proxyBean.































Property



Value



Description



proxyInterfaces



spring.catalog.CatalogInterface



Set of interfaces being proxied



interceptorNames



interceptor



List of beans used as interceptor beans for the
proxied bean



target



spring.catalog



Id of the bean to be proxied



proxyTargetClass



true



Creates class based proxies


To add a property:

Right-click on the bean
with id proxyBean and select Add child>property.



Figure 5

To add a
value right-click on property and select Add child>list.
To add a element to the element
right-click on list and select Add child>value. For
the interceptorName property add list value “interceptor”.

The target property
requires a ref sub-element. Right-click on property and select
Add child>ref. To the ref element we need to add the local
attribute. Right-click on ref and select Add
Attribute>local
. Similarly add the proxyTargetClass property
and set its value to true. The proxyBean with properties is
shown below.



Fig 6

To the bean for
JavaBean Catalog add constructor-arg sub-elements for arguments to
the constructor for the JavaBean. The constructor has parameters for
journal, publisher, edition, title and author.


<constructor-arg index="0" value="Oracle Magazine" />>
<constructor-arg index="1" value="Oracle Publishing" />
<constructor-arg index="2" value="November-December 2010" />
<constructor-arg index="3" value="Agile Architecture" />
<constructor-arg index="4" value="Bob Rhubart" />

The bean’s property
values may also be specified as property/value.


<property name="journal">
<value>Oracle Magazine</value>
</property>
<property name="publisher">
<value>Oracle Publishing</value>
</property>
<property name="edition">
<value>November-December 2010</value>
</property>
<property name="title">
<value>Agile Enterprise Architecture</value>
</property>

<property name="author">
<value>Bob Rhubart</value>
</property>

The bean definition
file is listed below.


<?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.5.xsd    


http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean id="spring.catalog" class="spring.catalog.Catalog">
<constructor-arg index="0" value="Oracle Magazine" />
<constructor-arg index="1" value="Oracle Publishing" />
<constructor-arg index="2" value="November-December 2010" />
<constructor-arg index="3" value="Agile Architecture" />
<constructor-arg index="4" value="Bob Rhubart" />
</bean>

<bean id="interceptor" class="spring.catalog.CatalogInterceptor"></bean>

<bean id="proxyBean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>spring.catalog.CatalogInterface</value>
</property>
<property name="interceptorNames">
<list>
<value>interceptor</value>
</list>
</property>

<property name="target">
<ref local="spring.catalog"></ref>
</property>
<property name="proxyTargetClass">
<value>true</value>
</property>
</bean>
</beans>

Creating a Method Interceptor

The
org.aopalliance.intercept.MethodInterceptor interface is used to
intercept calls on an interface prior to the target. The interceptor
bean class should implement the interface and implement the
invoke(MethodInvocation) method of the interface to modify the
behavior of a method.

Create an interceptor
Java class CatalogInterceptor that implements the MethodInterceptor
interface in the spring.catalog package. CatalogInterceptor.java get
added to the Spring project. In the invoke() method output the name
of the intercepted method and the name of the class containing the
intercepted method. The CatalogInterceptor method is listed below.


package spring.catalog;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class CatalogInterceptor implements MethodInterceptor {

@Override
public Object invoke(MethodInvocation inv) throws Throwable {

System.out.println("Intercepted method - "
+ inv.getMethod().getDeclaringClass()

+ " - " + inv.getMethod().getName());

return null;
}}

Creating a Spring Client




In this section we
shall create a Java client for the Spring bean and invoke the bean
methods. We shall instantiate the Spring bean that represents the
JavaBean spring.catalog.Catalog and invoke its method. Subsequently,
we shall instantiate the proxy bean proxyBean, which is configured
with an interceptor. We shall invoke the methods of the target class
to demonstrate that the method interceptor intercepts the method
calls and outputs the method name and the name of the containing
class.

First, create a Spring
client class SpringClient in the same package as the JavaBean and the
interceptor class. Add external JARs asm-3.3.jar and cglib-2.2.jar to
the Java Build Path.

We shall create two
versions of the SpringClient.java class. In the first version we
shall instantiate the JavaBean Catalog and invoke its methods to
demonstrate that the interceptor is not invoked. Instantiate the
Catalog bean using the elements or the
property/value in beanDefinition.xml as discussed earlier. Add a
method loadContext() to instantiate the Spring container, which is
essentially creating an ApplicationContext.


private void loadContext() {
String filename = "beanDefinition.xml";
context = new FileSystemXmlApplicationContext(filename);
}

In the main method
create an instance of the SpringClient class and invoke the
loadContext method.


SpringClient client = new SpringClient(); 
client.loadContext();

Instantiate the
JavaBean with id spring.catalog using the getBean method.


Catalog catalog = (Catalog) context.getBean("spring.catalog");

Output the bean
properties’ values.


System.out.println(catalog.journal);
System.out.println(catalog.publisher);
System.out.println(catalog.edition);
System.out.println(catalog.title);
System.out.println(catalog.author);

Invoke the
getTestMessage() and output the message returned.


String test = catalog.getTestMessage();
System.out.println(test);

The SpringClient.java
class is shown below.

package spring.catalog;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


public class SpringClient {

private static ApplicationContext context;

/**
* Load up the Spring container
*/

private void loadContext() {
String filename = "beanDefinition.xml";
context = new FileSystemXmlApplicationContext(filename);
}

public static void main(String[] args) {

  SpringClient client = new SpringClient();
  client.loadContext();
  //getBean spring.catalog Interceptor method not invoked.
 
Catalog catalog = (Catalog) context.getBean("spring.catalog");

System.out.println(catalog.journal);
  System.out.println(catalog.publisher);
  System.out.println(catalog.edition);
  System.out.println(catalog.title);
  System.out.println(catalog.author);

String test = catalog.getTestMessage();
System.out.println(test);

}
}

Right-click on the
SpringClient.java application and select Run As>Java
Application
.


As the Catalog JavaBean
is not configured with a method interceptor the method calls do not
get intercepted and the values returned by the accessor methods get
output.



Figure 7

We could also have used
a XmlBeanFactory method to instantiate the Spring bean, and also used
setter methods to set the bean properties’s values instead of
instantiating the bean in the beanDefinition.xml. The output would be
the same, but would include the message “Loading XML bean
definitions from class path resource (beanDefinition.xml)”.

In the second version
of the SpringClient application we shall instantiate the proxy bean
that is configured with the interceptor method. We shall reference
the proxy through the Spring container. Create a XmlBeanFactory
object.

XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("beanDefinition.xml"));

Instantiate the proxy
bean with the getBean method.

Catalog catalog = (Catalog) beanFactory.getBean("proxyBean");

Invoke the
getTestMessage method and output the value returned.

String test = catalog.getTestMessage();
System.out.println(test);

Invoke the setter
methods to set the values of the bean properties.

catalog.setJournal("Oracle Magazine");
catalog.setPublisher("Oracle Publishing");
catalog.setEdition("November-December 2010");
catalog.setTitle("Agile Enterprise Architecture");
catalog.setAuthor("Bob Rhubart");

Output the bean
properties.

System.out.println(catalog.journal);
System.out.println(catalog.publisher);
System.out.println(catalog.edition);
System.out.println(catalog.title);
System.out.println(catalog.author);

The SpringClient.java
is listed below.

package spring.catalog;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class SpringClient {

public static void main(String[] args) {

// reference the proxy through the Spring container
//getBean proxyBean Interceptor method invoked.

/** * Load up the Spring container */
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("beanDefinition.xml"));


//getBean proxyBean Interceptor method invoked.

Catalog catalog = (Catalog) beanFactory.getBean("proxyBean");

String test = catalog.getTestMessage();
System.out.println(test);

catalog.setJournal("Oracle Magazine");
catalog.setPublisher("Oracle Publishing");
catalog.setEdition("November-December 2010");
catalog.setTitle("Agile Enterprise Architecture");
catalog.setAuthor("Bob Rhubart");
System.out.println(catalog.journal);
System.out.println(catalog.publisher);
System.out.println(catalog.edition);
System.out.println(catalog.title);
System.out.println(catalog.author);
}
}

Right-click on
SpringClient.java and select Run As>Java Application.
As the proxy bean is configured with the interceptor method, the
method invocations get intercepted. The invoke method of the
CatalogInterceptor class gets invoked. The method name and the name
of the containing class are the output. The bean properties’ values
are not in the output as the method invocations are intercepted.



Figure 8.

aop Namespace

Spring implements AOP
using a spring-aop schema and the aop namespace. Alternatively, AOP
may be implemented using the @Aspect annotation.


In this section we
shall use the aop namespace to implement AOP. We will develop a Web
application consisting of a JSF page for user input, and
applicationContext.xml to create a BeanFactory and an
ApplicationContext. Some of the aop namespace tags are discussed in
the following table.













































Tag



Description



aop:aspectj-autoproxy



Enables @AspectJ aspects in Spring with
autoproxying beans.



aop:config



All aspects and advisors must be declared
within aop:config



aop:pointcut



Declares a pointcut



aop:aspect



Declares an aspect



aop:after-returning



Declares advice that runs after matched method
execution completes normally



aop:after-throwing



Declares advice that runs after matched method
execution exits by throwing an exception



aop:advisor



Declares an advisor



aop:before



Declares advice that runs before matched method
execution



aop:after



Declares advice that runs no matter how the
matched method execution exits


Creating a Spring & JSF Faceted Web Project

Now we will create a
Web project, SpringJSF, for the Spring AOP similar to the Spring
project that we created for the method interceptor example.


  1. Select Web>Dynamic
    Web Project
    in New wizard.
  2. In New Dynamic Web
    Project specify a Project name, SpringJSF, and configure a
    target runtime for Oracle WebLogic Server 11gR1 Patch Set 2.
  3. Select the Default
    Configuration…
    and click on Next.
  4. Accept the default
    Java settings (source folder as src and output folder as
    build/classes). Click on Next.
  5. Specify a Context
    Root (SpringJSF) and a Content directory, select the checkbox
    Generate web.xml deployment descriptor, and click on Finish.
    A Web project for Spring AOP gets created.
  6. Now right-click on
    SpringJSF in the Project Explorer and select Properties.
  7. Select Project
    Facets
    . Configure the Spring facet as discussed previously. Also
    select the JSF 1.2 facet.
  8. Click on Further
    configuration required
    .
  9. In JSF Capabilites
    select JSF Implementation Library Type as User Library and
    click on the Download library... button.
  10. Select the JSF
    1.2 (Mojarra JSF API Implementation)
    and click on Next.
  11. Accept the terms
    of the license and click on Finish. The JSF 1.2 library gets
    added to the project.
  12. Click on Next.
    In the Spring configuration select the checkbox Create a Spring
    bean definition file
    and select the default file
    applicationContext.xml.
  13. Click on OK.
  14. In
    Properties>Project Facets click on Apply to install the
    project facets JSF 1.2 and Spring 2.5.
  15. Click on OK
    to configure the target runtimes with the project facet libraries. A
    Spring and JSF faceted Web project gets created. The JSF and Spring
    libraries are also shown added to the project.




Figure 9.

The
web.xml file gets updated with a contextConfigLocation context
parameter that specifies the location of the applicationContext.xml
file. Also, a listener class
org.springframework.web.context.ContextLoaderListener gets
configured. The listener class is the bootstrap listener to start up
Spring’s root
org.springframework.web.context.WebApplicationContext. The Spring AOP
framework requires the AspectJ library in the classpath. Add the
AspectJ library and dependencies shown below to the Java Build path.



Figure 10.

Creating a Bean Class

In this section we
shall create a JavaBean that we shall configure as a Spring bean and
use in a pointcut expression.

Create a Java class
Catalog.java by selecting Java>Class in New wizard. To
Catalog.java JavaBean add properties for journal, publisher, edition,
title, and author. Also, add accessor methods for the JavaBean
properties. The getter accessor methods should return the initial
values for the bean properties. The Catalog JavaBean’s properties
may alternatively be instantiated using property/value or
constructor-arg in the applicationContext.xml. The JavaBean class
Catalog.java is shown below.

package spring.catalog;

public class Catalog {

public String journal;
public String publisher;
public String edition;
public String title;
public String author;

public Catalog() {
}

public Catalog(String journal, String publisher, String edition,
String title, String author) {

this.journal = journal;
this.publisher = publisher;
this.edition = edition;
this.title = title;
this.author = author;
}

public java.lang.StringBuffer getAuthor() {
return new StringBuffer("Bob Rhubart");
}

public java.lang.StringBuffer getEdition() {
return new StringBuffer("November-December 2010");
}

public java.lang.StringBuffer getJournal() {
return new StringBuffer("Oracle Magazine");
}

public java.lang.StringBuffer getPublisher() {
return new StringBuffer("Oracle Publishing");
}

public java.lang.StringBuffer getTitle() {
return new StringBuffer("Agile Enterprise Architecture");
}

public void setAuthor(String author) {
this.author = author;
}

public void setEdition(String edition) {
this.edition = edition;
}

public void setJournal(String journal) {
this.journal = journal;
}

public void setPublisher(String publisher) {
this.publisher = publisher;
}

public void setTitle(String title) {
this.title = title;
}
}

Creating a AOP JavaBean

In this section we
shall create a JavaBean that we will configure with the Spring
framework in applicationContext.xml as a Spring AOP aspect. Create a
Java class CatalogAOP.java in the same package as the Catalog.java
JavaBean. The pointcut expression is used to match join
points
and the advice is the action taken by the aspect.
The aspect’s pointcut expression and advice type are configured in
the applicationContext.xml, in the next section. We shall be
configuring aop:after-returning advice for each of the getter
accessor methods in the Spring bean Catalog that return values for
bean properties as SpringBuffer.

In the advice we shall
invoke the setter methods of the Spring aspect bean CatalogAOP.java
with the values returned by the getter methods of the Catalog
JavaBean as arguments. The Spring AOP framework shall invoke the
setter methods of the Spring aspect bean CatalogAOP dynamically after
returning from the getter methods of the Spring bean Catalog.

In the setter methods
in the aspect bean we shall first output the bean property values
returned by the Catalog bean prepended by the method name and
subsequently modify the bean property values by adding labels to
precede the bean properties. For example, the setTitle(String title)
method modifies the Catalog JavaBean’s title property by prepending
it with "Title: ".

public void setTitle(StringBuffer title) {
System.out.println("setTitle method invoked" + title);
title.insert(0, "Title: ");
}

The CatalogAOP.java
Spring AOP aspect is shown below.

package spring.catalog;

public class CatalogAOP {

public String journal;
public String publisher;
public String edition;
public String title;
public String author;

public CatalogAOP() {
}

public CatalogAOP(String journal, String publisher, String edition,
String title, String author) {

this.journal = journal;
this.publisher = publisher;
this.edition = edition;
this.title = title;
this.author = author;
}

public String getAuthor() {
return author;
}

public String getEdition() {
return edition;
}

public String getJournal() {
return journal;
}

public String getPublisher() {
return publisher;
}

public String getTitle() {
return title;
}

public void setEdition(StringBuffer edition) {
System.out.println("setEdition method invoked" + edition);
//edition.insert(0, "Edition: ");
}

public void setJournal(StringBuffer journal) {
System.out.println("setJournal method invoked" + journal);
//journal.insert(0, "Journal: ");
}

public void setPublisher(StringBuffer publisher) {
System.out.println("setPublisher method invoked" + publisher);
// publisher.insert(0, "Publisher: ");
}

public void setTitle(StringBuffer title) {
System.out.println("setTitle method invoked" + title);
// title.insert(0, "Title: ");
}

public void setAuthor(StringBuffer author) {
System.out.println("setAuthor method invoked" + author);
//author.insert(0, "Author: ");
}
}

Creating a Bean
Definition File

The Spring AOP
including the pointcuts, aspects, and advices are configured in the
Spring configuration file applicationContext.xml. For using the
Spring AOP framework we need to enable AspectJ support.

First, configure a
Spring bean for the CatalogAOP JavaBean, which we shall subsequently
configure as an aspect. To enable the AspectJ support add the
aop:aspectj-autoproxy element. Add the ‘<’ and select
aop:aspectj-proxy element from the pop-up.



Figure 11.

All aspects and
advisors are declared within the aop:config element. Add the
aop:config element to the Spring configuration file. Add a ‘<’
and select the aop:config element from the pop-up.



Figure 12.

If the target object
does not use any interfaces Spring AOP uses CGLIB to create the proxy
for the target object. To specify the use of CGLIB set the
proxy-target-class attribute of aop:config to “true”. Right-click
on aop:config and select Add Attribute>proxy-target-class.



Figure 13.

Next, add a pointcut
defintion to the aop:config element. A pointcut is used to match join
points; a join point in Spring AOP is a method execution.

A pointcut definition
within a aop:config may be used for several aspects and advisors. We
shall use the “bean” pointcut designator (PCD) to specify the
Catalog Spring bean for matching join points. Right-click on
aop:config and select Add Child>pointcut.



Figure 14.

Specify the value of
the expression attribute as bean(catalogBean). Next, add an aspect.
Right-click on aop:config and select Add Child>aspect.



Figure 15.

To the aop:aspect
element add a ref attribute to refer to the Spring bean
catalogBeanAOP, which is the aspect Spring bean. Right-click on
aop:aspect and select Add Attribute>ref. The Spring
bean catalogBeanAOP gets configured as an aspect.




Figure 16.

Next, we shall
configure after-returning advice for each of the getter methods of
Spring bean catalogBean, which is the JavaBean Catalog. Right-click
on aop:aspect and select Add Child>after-returning.
After returning advice is the advice to be run when a method returns
without throwing an exception.



Figure 17.

To the after-returning
element add the attributes explained in the following table, which
applies for one join point.































Attribute



Value



Description



pointcut



execution(java.lang.StringBuffer
getJournal(..))



Specifies the pointcut expression to match a
join point, which is the method call to getJournal that returns a
StringBuffer



method



setJournal



The method of the aspect to invoke



returning



journal



The advice method parameter to which the return
value of the getJournal method is passed as an argument. The type
of the returned value should match the parameter type.



arg-names



journal



Specifies argument names for the advice method


Similarly, add
after-returning advice for other join points. The Spring
configuration file with after-returning advice for all the join
points is listed below.

<?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.5.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
&...
id="catalogBean" class="spring.catalog.Catalog">
<!--
<property name="journal"> <value>Oracle Magazine</value> </property>
<property name="publisher"> <value>Oracle Publishing</value>
</property> <property name="edition"> <value>November-December
2010</value> </property> <property name="title"> <value>Agile
Enterprise Architecture</value> </property> <property name="author">
<value>Bob Rhubart</value> </property>

<constructor-arg index="0" value="Oracle Magazine" />
<constructor-arg index="1" value="Oracle Publishing" />
<constructor-arg index="2" value="November-December 2010" />
<constructor-arg index="3" value="Agile Enterprise Architecture" />
<constructor-arg index="4" value="Bob Rhubart" />-->
</bean>

<bean id="catalogBeanAOP" class="spring.catalog.CatalogAOP"/>

<aop:aspectj-autoproxy />
<aop:config proxy-target-class="true">
<aop:pointcut expression="bean(catalogBean)" id="catalogBeanPc"></aop:pointcut>
<aop:aspect ref="catalogBeanAOP" id="catalogBeanAspect">
  <aop:after-returning pointcut="execution(java.lang.StringBuffer getJournal(..))"
method="setJournal" returning="journal" arg-names="journal" />
  <aop:after-returning pointcut="execution(java.lang.StringBuffer getPublisher(..))"
method="setPublisher" returning="publisher" arg-names="publisher" />
  <aop:after-returning pointcut="execution(java.lang.StringBuffer getEdition(..))"
method="setEdition" returning="edition" arg-names="edition" />
  <aop:after-returning pointcut="execution(java.lang.StringBuffer getTitle(..))"
method="setTitle" returning="title" arg-names="title" />
  <aop:after-returning pointcut="execution(java.lang.StringBuffer getAuthor(..))"
method="setAuthor" returning="author" arg-names="author" />
</aop:aspect>
</aop:config>
</beans>

Creating a JSF Page

In this section we
shall create a JSF page to output the Spring bean catalogBean
(Catalog.java JavaBean) properties. We shall demonstrate the effect
of the aspect Spring bean catalogAOPBean on the catalogBean’s
propeties’ values.


  1. Select
    File>New
    . In New wizard select Web>JSP and click on
    Next.
  2. Select the
    SpringJSF/WebContent folder and specify File name as catalog.jsp
    and click on Next.
  3. Click on Finish.
    A JSP catalog.jsp get added to the SpringJSF project.

In the catalog.jsp
output the values for the catalogBean properties using the
h:outputText element. Catalog.jsp is listed below.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" version="2.0">
    <jsp:output omit-xml-declaration="true" doctype-root-element="HTML" doctype-system="http://www.w3.org/TR/html4/loose.dtd" doctype-public="-//W3C//DTD HTML 4.01 Transitional//EN"/>
    <jsp:directive.page language="java"
        contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" />
 
<f:view>
    <html>
      <head>
        <meta http-equiv="Content-Type"
              content="text/html; charset=ISO-8859-1"/>
        <title>Catalog</title>
      </head>
      <body>
        <h:form><table>
       
          <tr><td> <h:outputText value="#{catalogBean.journal}"/></td></tr>
           <tr><td><h:outputText value="#{catalogBean.publisher}"/></td></tr>
          <tr><td> <h:outputText value="#{catalogBean.edition}"/></td></tr>
           <tr><td><h:outputText value="#{catalogBean.title}"/></td></tr>
           <tr><td><h:outputText value="#{catalogBean.author}"/></td></tr>
       
        </table></h:form>
      </body>
    </html>
  </f:view>

</jsp:root>

To the faces-config.xml
add the following application element so that EL expressions also
recognize Spring beans as managed beans.

<application><el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver></application>

Running the JSF Page

In this section we
shall run the catalog.jsp to demonstrate the effect of the aspect on
the Spring bean catalogBean’s properties. In the first run comment
out the modifications, which prepend labels to the Spring bean’s
property values in the CatalogAOP JavaBean’s setter methods.

//edition.insert(0, "Edition: ");
//journal.insert(0, "Journal: ");
//publisher.insert(0, "Publisher: ");
//title.insert(0, "Title: ");
//author.insert(0, "Author: ");

Right-click on
catalog.jsp and select Run As>Run on Server. Start
the WebLogic server if not already started and click on Finish.
The SpringJSF application gets deployed to the WebLogic server as an
auto-generated EAR file. The server output shows that the setter
methods of the Spring AOP aspect bean get invoked and the Spring bean
catalogBean’s property values are the output.



Figure 18.

Run the catalog.jsp
with url http://localhost:7001/SpringJSF/faces/catalog.jsp.
The Spring bean catalogBean’s property values are in the output.



Figure 19.

In the second run
uncomment the modifications to the catalogBean’s property values in
the aspect Spring bean catalogAOPBean; modifications that prepend
labels. The aspect gets applied and the catalogBean’s property
values get prepened with labels, as shown in the output.



Figure 20.

In this article you
learnt about the Spring AOP framework related features, which is one
of the main components that distinguishes Spring from Java EE.
Infact, SpringSource claims that "...Spring AOP provides an
excellent solution to most problems in Java EE applications that are
amenable to AOP."

Deepak Vohra is a NuBean consultant and a web developer.
Related Topics >> J2EE   |   Programming   |   Featured Article   |