Understanding of Spring AOP

Source: Internet
Author: User

This is a tutorial on Spring AOP programming found online, and after reading this article, Spring AOP is no longer difficult to understand, so I translated it into Chinese and recommended it to Spring AOP beginners.

AOP is becoming the next holy grail of software development. With AOP, you can inject code that processes aspect into the main program, and usually the main purpose of the main program is not to handle these aspect. AOP can prevent code clutter. to understand how AOP does this, consider the work of logging. The log itself is unlikely to be the main task of the main program you develop. It would be nice if you could inject the "invisible", common log code into the main program. AOP can help you do that. The Spring framework is a promising AOP technology. As a non-aggressive, lightweight AOP framework, you can use it in a Java program without using a pre-compiler or other meta tags. This means that only one person in the development team has to deal with the AOP framework, and others are programmed as usual. AOP is the source of many terms that are intuitively incomprehensible. Fortunately, you can write an AOP module just by understanding the three concepts. These three concepts are: Advice,pointcut and advisor. Advice is the code you want to inject into different parts of the program. Pointcut defines where the advice needs to be injected, usually a public method for a particular class. Advisor is an assembler of pointcut and advice, which is the code that injects advice into a predefined location in the main program.

Now that we know the need to use the advisor to inject "invisible" advice into the main code, let's implement a spring AOP example. In this example, we will implement a before advice, which means that the code for advice is executed before the public method being invoked is started. Here is the implementation code for this before advice: code: Package com.company.springaop.test;

Import Java.lang.reflect.Method; import Org.springframework.aop.MethodBeforeAdvice;

public class Testbeforeadvice implements Methodbeforeadvice {

public void before (Method m, object[] args, Object target) throws Throwable { System.out.println ("Hello wo rld! (by " + This.getclass (). GetName () +") ");     }  }   

Interface Methodbeforeadvice There is only one method before need to implement, it defines the implementation of advice. The Before method uses three parameters, which provide quite a wealth of information. The parameter method m is the advice that executes after the start of the process. The method name can be used as a condition to determine whether code is executed. Object[] args is an array of arguments passed to the public method being called. The parameter args and the name of the executed method are useful information when logging is required. You can also change the parameters passed to M, but use this function with care; the programmer who wrote the original main program did not know that the main program might conflict with the incoming parameters. Object target is a reference to the execution method M object.

In the following Beanimpl class, advice is executed before each public method call: code: Package com.company.springaop.test;

public class Beanimpl implements Bean {

public void Themethod () { System.out.println (This.getclass (). GetName () + "." + New Exception (). getst Acktrace () [0].getmethodname () + "()" + "says Hello!");     }  }

Class Beanimpl implements the following interface bean: code: Package com.company.springaop.test;

Public interface Beans {public void Themethod (); }

While it is not necessary to use interfaces, the interface-oriented rather than implementation-oriented programming is good programming practice, and spring encourages this.

Pointcut and advice are implemented through configuration files, so the next thing you need to do is write the Java code for the Main method: code:

Package com.company.springaop.test;

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

public class Main {

public static void Main (string[] args) { //read the configuration file ApplicationContext ctx = new Filesystemxmlapplicationcontext ("Springconfig.xml");

Instantiate an object Bean x = (bean) Ctx.getbean ("Bean");

Execute the public method of the bean (the test) X.themethod (); }  }

We start by reading and processing the configuration file, and we're going to create it right now. This configuration file will be used as "glue" in different parts of the glue program. After reading and processing the configuration file, we will get a create factory CTX. Any spring-managed object must be created through this factory. Objects can be used normally after they are created by the factory.

Just use the configuration file to assemble each part of the program. Code:

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

<beans><!--config--><bean id= "Bean" class= "Org.springframework.aop.framework.ProxyFactoryBean" ><property name= "Proxyinterfaces" ><value>com.company.springaop.test.Bean</value>      </property>       <property name= "target" >        <ref local=" Beantarget "/>      </property>      <property name= "interceptornames" >         <list>           <value>theadvisor</value>         </list>      </property>    </bean>

<!--class--> <bean id= "Beantarget" class= " Com.company.springaop.test.BeanImpl"/>

<!--advisor-->    <!--note:an Advisor assembles Pointcut and Advice-->    <bean id= "Theadvisor" class= " Org.springframework.aop.support.RegexpMethodPointcutAdvisor ">      <property name= "advice" >         <ref local= "Thebeforeadvice"/>      </property>      <property name= "pattern" >< Span class= "Apple-converted-space" >        <value>com/.company/.springaop/. test/. Bean/.themethod</value>      </property>< Span class= "Apple-converted-space" >    </bean>

<!--advice--> <bean id= "Thebeforeadvice" class= "Com.company.springaop.test.TestBeforeAdvice"/> </beans>

The order of the four bean definitions is not important. We now have a advice, a advisor with regular expression Pointcut, a main program class and a configured interface, which, through the factory CTX, returns a reference to its own implementation.

Both Beanimpl and Testbeforeadvice are directly configured. We create a bean element with a unique ID and specify an implementation class. That's the whole job.

The Advisor is implemented through a Regexmethodpointcutadvisor class provided by the spring framework. We use a property of the advisor to specify the Advice-bean it needs. The second attribute defines the pointcut with regular expressions to ensure good performance and legibility.

The last configuration is the bean, which can be created through a factory. The bean definition looks more complex than it actually is. A bean is an implementation of Proxyfactorybean, which is part of the spring framework. The behavior of this bean is defined by the following three attributes:

The Proxyinterface property defines the interface class. The property target points to a locally configured bean that returns an implementation of an interface. Property Interceptornames is the only property that allows you to define a list of values. This list contains all the advisors that need to be executed on the beantarget. Note that the order of the Advisor list is very important.

Spring Tools

While you can manually modify the ant build script, using Springui (Springui is now part of the spring framework and renamed Spring-ide), using spring AOP becomes simple, just a few clicks away. You can install Springui as a plug-in in eclipse. Then, you just right-click on your Project and select "Add Spring Project Nature". In the Project properties, you can add a spring configuration file under Spring Project. Add the following class libraries to Project:aopalliance.jar,commons-logging.jar,jakarta-oro-2.0.7.jar and Spring.jar before compiling. When you run the program you will see the following information:

... (Logging information) Hello world! (by Com.company.springaop.test.TestBeforeAdvice) Com.company.springaop.test.BeanImpl.theMethod () says Hello!

Pros and cons

Spring is more advantageous than other frameworks because it provides more functionality than AOP. As a lightweight framework, it can play a role in different parts of the Java EE. So, even if you don't want to use spring AOP, you might want to use spring. Another advantage is that spring does not require that all people in the development team will use it. Learning spring should start from the first page of spring reference. After reading this article, you should be able to better understand the spring reference. The only downside to spring is the lack of more documentation, but its mailing list is a good addition and will continue to show more documents.

Understanding of Spring AOP

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.