Spring AOP Framework

Source: Internet
Author: User
Tags add aop object contains expression implement interface unique id
AOP is becoming the next holy grail of software development. With AOP, you can inject code that handles aspect into the main program, and usually the main purpose of the main program is not to deal with these aspect. AOP can prevent code clutter. To understand how AOP does this, consider the work of journaling. The log itself is unlikely to be the main task of the main program you developed. It would be nice if you could inject "invisible", generic 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 Java programs without using a precompiled or other meta tag. 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 root of many terms that are hard to understand by intuition. Fortunately, you can write an AOP module just by understanding 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 a advice needs to be injected, usually a public method of a particular class. The advisor is the pointcut and advice assembler, which is the code that injects the advice into a predefined location in the main program. Now that we know the need to use advisor to inject "invisible" advice into the main code, let's implement an example of Spring AOP. In this example, we will implement a before advice, which means that the advice code is executed before the called public method begins. The following 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 ta Rget)   throws Throwable {    System.out.println ("Hello world! (by "    &NBSP   + This.getclass (). GetName ()         + ")";  }   Interface Methodbeforeadvice only one method before need to implement, which defines the implementation of advice. The Before method is a total of three parameters, and they provide quite a lot of information. The parameter method m is a way to execute after advice starts. 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 called public method. When logging is required, the parameter args and the name of the method being executed are very useful information. You can also change the parameters passed to M, but use this function with care; programmers who wrote the original main program did not know that the main program might conflict with incoming arguments. Object target is a reference to the Execute Method M object. In the following Beanimpl class, the advice: code: Package Com.company.springaop.test is executed before each public method call; public class Beanimpl implements beans {  public void Themethod () {    System.out.println this.getclass (). GetName ()         + "." + New Exception (). Getstacktrace () [0].getmethodname ()       &NBS P + "()"         + "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, it is a good programming practice for interfaces rather than implementation-oriented programming that spring also encourages. Pointcut and advice are implemented through a configuration file, so the next thing you need to do is write the main method's Java code: 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   &NB Sp 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 will create it immediately. This configuration file will be used as glue for 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 a factory. Each part of the program can be assembled using only the configuration file. 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--> &NB Sp <bean id= "Beantarget" class= "Com.company.springaop.test.BeanImpl"/>   <!--advisor-->   <!-- Note:an Advisor assembles Pointcut and advice-->   <bean id= "Theadvisor" Org.springframework.aop.support.RegexpMethodPointcutAdvisor ">     <property name=" Advice ">       <ref local= "Thebeforeadvice"/>     </property>     <property name= "pattern" >       <value>com\.company\.springaop\.test\. bean\.themethod</value>     </property>   </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, an advisor that contains regular expression pointcut, a main program class and a configured interface, which, through 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 all the work. Advisor is implemented through a Regexmethodpointcutadvisor class provided by the spring framework. We use a property of advisor to specify the Advice-bean that it needs. The second property defines the pointcut with a regular expression, ensuring good performance and readability. The last configuration is the bean, which can be created from a single factory. The bean definition looks more complicated than it actually is. The Bean is an implementation of Proxyfactorybean, which is part of the spring framework. The bean's behavior is defined by the three attributes: the attribute proxyinterface defines the interface class. Attribute target points to a locally configured bean that returns the implementation of an interface. Property Interceptornames is the only property that allows you to define a list of values. This list contains all the advisor that needs to be executed on the beantarget. Note that the order of the Advisor list is very important. Spring Tools Although 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 becomesIt's simple, just click the mouse. You can install Springui into one of the plug-in of Eclipse. Then, you just right-click on your Project and choose Add Spring Project nature. In the Project properties, you can add the spring configuration file under "Spring Project." Before compiling, add the following class library to Project:aopalliance.jar,commons-logging.jar,jakarta-oro-2.0.7.jar and Spring.jar. When you run the program you will see the following message: ... (Logging information) Hello world! (by Com.company.springaop.test.TestBeforeAdvice) Com.company.springaop.test.BeanImpl.theMethod () says hello! The pros and cons Spring has an advantage over other frameworks because it provides more functionality than AOP. As a lightweight framework, it can play a role in different parts of 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 all people in the development team to use it. Learn spring should start with the first page of spring reference. After reading this article, you should be able to better understand the spring reference. Spring's only drawback is the lack of more documentation, but its mailing list is a good addition and will continue to show more documentation.

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.