Aspect-oriented programming in the Spring framework

Source: Internet
Author: User
Tags aop object execution expression object object string version throwable
As the first part of this series that introduces aspect-oriented programming in the Spring Framework (aspect-oriented PROGRAMMING,AOP), this article describes the basics of enabling you to use aspect-oriented features in spring for rapid development. Using the tracking and logging aspects (aspect-oriented HelloWorld) as an example, this article demonstrates how to use the features unique to the spring framework to declare pointcuts and notifications for application. The second part of this series will give you a more in-depth overview of how to use all the notification types and pointcuts in spring to implement more practical aspects and aspect-oriented design patterns. For a more general introduction to AOP, check out Graham O ' Regan's article on the Onjava site, "Introduction to aspect-oriented programming."

The purpose of this article is not to introduce all the important elements that make up the modular Java EE System-the spring framework-and we will focus only on the AOP features that spring provides. Because of the modular design approach of spring, we can use only the AOP elements of the framework without having to think too much about the other modules that make up the spring framework.

What does spring offer in terms of AOP?

"Its goal is not to provide the most sophisticated AOP implementations (although Spring AOP is very powerful), but to provide an AOP implementation that is tightly integrated with the spring IOC to help address common problems in enterprise applications. ”

Spring Framework Reference documentation

To achieve this goal, the spring framework currently supports a set of AOP concepts, from pointcuts to notifications. This article will show you how to use the following AOP concepts implemented in the Spring framework:

Notification (Advice): How to declare before notifications, afterreturning notifications, and afterthrowing notifications as beans.

Pointcut (Pointcut): How to declare static pointcut logic to associate all the contents of an XML Spring Bean configuration file.

Advisor: The association pointcut defines how the bean is notified.

Setting up a scenario: a simple example application

"In general, Spring is not a predefined description. While it is easy to use good practice, it avoids the imposition of a specific method. ”

Spring Framework Reference documentation

To try the AOP features of the spring framework, we first want to create a simple Java application. The Ibusinesslogic interface and the Businesslogic class provide a simple widget block for the Bean in the spring framework. Although this interface is not necessary for our simple application logic, it is a good practice recommended by the Spring framework.

public interface Ibusinesslogic
{
public void foo ();
}

public class Businesslogic
Implements Ibusinesslogic
{
public void Foo ()
{
System.out.println ("Inside Businesslogic.foo ()");
}
}


You can write the MainApplication class to practice the public method of businesslogic beans.

Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.FileSystemXmlApplicationContext;

public class MainApplication
{
public static void Main (String [] args)
{
Read the configuration file
ApplicationContext ctx =new filesystemxmlapplicationcontext ("Springconfig.xml");

Instantiate an Object
Ibusinesslogic Testobject = (ibusinesslogic) ctx.getbean ("Businesslogicbean");

Execute the public
Method of the Bean
Testobject.foo ();
}
}


There is nothing to be aware of in the Businesslogic class and its associated interfaces. However, the way the MainApplication class initializes businesslogic objects is interesting. By using Ctx.getbean ("Businesslogicbean") calls, mainapplication the task of loading and managing the bean instance of the Businesslogic class to the spring framework.

Allow spring to control the initialization of businesslogic beans, which gives the spring runtime an opportunity to perform all the bean-related administrative tasks required by the Java EE system before the bean is returned to the application. The spring runtime configuration then determines which tasks and modules are applied to the bean. This configuration information is provided by an XML file, similar to the following:

! DOCTYPE Beans Public
"-//spring//dtd bean//en"
"Http://www.springframework.org/dtd/spring-beans.dtd" >



!--Bean Configuration-->
Ibusinesslogic





!--Bean Classes-->


The profile, Springconfig.xml, specifies the bean to load an interface that matches the ibusinesslogic. The bean is then associated to the Businesslogic implementation class. Looks like it was a lot of effort. Just to load a simple bean and invoke a method, but you know, this configuration file is just one embodiment of the many features that make the spring framework transparent to applications applying its components.

Figure 1 shows the basic sequence diagram: MainApplication execution, no application.





Figure 1. No sequence diagram for Businesslogic bean application

Application method Tracking (tracing) aspect

Perhaps the most basic aspect is the method of tracking. This may be the simplest aspect you can find, so it is a good starting point for studying the new AOP implementation.

Method Trace aspect captures the call to the tracked method and the return value of the method within a target application, and displays this information in some way. In AOP, the before and after types of notifications are used to capture the join points of these types, since both notifications can be triggered before or after the method call join point. With the spring framework, the before notification of method tracking is declared in the Tracingbeforeadvice class.

Import Java.lang.reflect.Method;
Import ORG.SPRINGFRAMEWORK.AOP. Methodbeforeadvice;

public class Tracingbeforeadvice
Implements Methodbeforeadvice
{
public void before (method m,object[] Args,object target)
Throws Throwable
{
System.out.println ("Hello world! (By "+this.getclass" (). GetName () + ")");
}
}


Similarly, after notification can be declared in the Tracingafteradvice class.

Import Java.lang.reflect.Method;
Import Org.springframework.aop.AfterReturningAdvice;

public class Tracingafteradvice
Implements Afterreturningadvice
{
public void afterreturning (Object object,method m,object[] args,object target)
Throws Throwable
{
System.out.println ("Hello world! (By "+this.getclass" (). GetName () + ")");
}
}


Each of these two classes represents a specific notification by implementing the appropriate notification interface for the spring framework. Each type of notification specifies the implementation of before (..) or afterreturning (..) Method so that the spring runtime can tell the notification when the appropriate join point will appear. Notably, Tracingafteradvice is actually extended from Afterreturningadvice to run the notification only if the join point obtains the return value without exception.

To associate a notification with an appropriate join point in an application, you must make some modifications to the springconfig.xml.

<?xml version= "1.0" encoding= "UTF-8"?
! DOCTYPE Beans Public
"-//spring//dtd bean//en"
"Http://www.springframework.org/dtd/spring-beans.dtd" >

<beans>

!--Bean Configuration-->
<bean id= "Businesslogicbean" class= "Org.springframework.aop.framework.ProxyFactoryBean"
<property name= "Proxyinterfaces"
<value> Ibusinesslogic </value>
</property>
<property name= "target" >
<ref local= "Beantarget"/>
</property>
<property name= "Interceptornames"
<list>
<value> Thetracingbeforeadvisor </value>
<value> Thetracingafteradvisor </value>
</list>
</property>
</bean>
!--Bean Classes-->
<bean id= "Beantarget"
class= "Businesslogic"/>

!--Advisor pointcut definition for before advice-->
<bean id= "Thetracingbeforeadvisor" class= "Org.springframework.aop.support.RegexpMethodPointcutAdvisor"
<property name= "Advice"
<ref local= "Thetracingbeforeadvice"/>
</property>
<property name= "pattern" >
<value>. * </value>
</property>
</bean>

!--Advisor pointcut definition for after advice-->
<bean id= "Thetracingafteradvisor" class= "Org.springframework.aop.support.RegexpMethodPointcutAdvisor"
<property name= "Advice"
<ref local= "Thetracingafteradvice"/>
</property>
<property name= "pattern" >
<value>. * </value>
</property>
</bean>

The!--Advice classes-->
<bean id= "Thetracingbeforeadvice" class= "Tracingbeforeadvice"
<bean id= "Thetracingafteradvice" class= "Tracingafteradvice"
</beans>


Thetracingbeforeadvisor and Thetracingafteradvisor Advisor are added to the Businesslogicbean stated earlier. Each advisor may intercept the join point to which all beans are associated. The advisor itself is the bean, and its only function is to associate the Pointcut definition with the notification bean. The pointcut definition in this example is a regular expression that specifies the associated join point in the static object hierarchy.

Because the Org.springframework.aop.support.RegexpMethodPointcutAdvisor pointcut Advisor is used in this example, the pointcut logic is specified using a regular expression. The regular expression is used to identify the connection point of the public interface to the Ibusinesslogici interface. Here are some examples of regular expressions that you can use to specify a collection of different join points on the Ibusinesslogic interface:

   .*: This expression selects all the join points on one or more beans to which the advisor is associated.

   ./ibusinesslogic/.foo: This expression selects only the join point of the Foo () method on the Ibusinesslogic interface. If the bean the advisor is associated with, the expression selects only the join point on the Ibusinesslogic interface.

The last bean declaration in the Springconfig.xml file specifies the class that implements the notification bean.

Now that the correct configuration of the trace has been specified, the next time the mainapplication is executed, these aspects will be woven into the initialization process, and all the methods in the Businesslogic bean will be tracked, as shown in Figure 2.



Figure 2. Sequence diagram of method tracking aspects applied to the businesslogic bean

Aspects of Reuse

The method tracking aspect can be extended to provide a slightly more complex record (Logging) aspect. The logging aspect provides a good example of reuse, because many of the features required for logging are already included in method tracking.

In this case, the record aspect extends the method tracking aspect to show the additional information associated with the exception that was thrown during the execution of the application.

To fully use the logging aspect, you need to make some changes to your application. The businesslogicexception exception class provides an exception that can be thrown by the void bar () method that is added by the Ibusinesslogicinterface interface and the Businesslogic implementation class.

public class Businesslogicexception
Extends Exception
{}

public interface Ibusinesslogic
{
public void foo ();

public void Bar ()
Throws Businesslogicexception;
}

public class Businesslogic
Implements Ibusinesslogic
{
public void Foo ()
{
System.out.println ("Inside Businesslogic.foo ()");
}

public void Bar ()
Throws Businesslogicexception
{
System.out.println ("Inside Businesslogic.bar ()");
throw new Businesslogicexception ();
}
}


The MainApplication class will now make an extra call to the Void Bar () method and handle the selected exception that might be thrown by the method.

Import Org.springframeworkcontext.ApplicationContext;
Import Org.springframework.context.support.FileSystemXmlApplicationContext;

public class MainApplication
{
public static void Main (String [] args)
{
Read the configuration file
ApplicationContext CTX = new Filesystemxmlapplicationcontext ("Springconfig.xml");

Instantiate an Object
Ibusinesslogic Testobject = (ibusinesslogic) ctx.getbean ("Businesslogicbean");

Execute the public methods of the bean
Testobject.foo ();

Try
{
Testobject.bar ();
}
catch (businesslogicexception ble)
{
System.out.println ("Caught Businesslogicexception");
}
}
}


Tracingbeforeadvice and Tracingafteradvice notifications from method tracking can be reused as a whole. The Loggingthrowsadvice class provides notifications for new exception records.

Import Org.springframework.aop.ThrowsAdvice;
Import Java.lang.reflect.Method;

public class Loggingthrowsadvice
Implements Throwsadvice
{
public void Afterthrowing (method method,object[] Args,object target,throwable Subclass)
{
System.out.println ("Logging that a" +subclass + "Exception is thrown.");
}
}


The final step in applying records is to modify the Springconfig.xml configuration file to include newly added loggingthrowsadvice notifications.

Figure 3 shows a UML sequence diagram that runs MainApplication and uses the spring framework to apply records.



Figure 3. Sequence diagram of the record aspect after applying to the businesslogic bean

The record aspect here clearly illustrates how to reuse the existing aspects and how to use the throws form of notifications in the spring framework. Overriding existing method-tracking implementations by declaring new notifications for before and after notifications enables more complex logging and records to more complex record frames, such as log4j.

Conclusion

This article illustrates some of the simple aspects of using the basic AOP architecture in the spring framework. In the next article in this series, we'll introduce some more practical aspects, explore aspects of the lifecycle, use the spring framework's around notifications, and use spring to apply AOP patterns.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.