Getting started with SpringAOP (transfer)

1. A preliminary study of Spring AOP

        Using AOP, you can inject code that handles aspects into the main program, which is usually not the main purpose of the main program to handle these aspects. AOP prevents code clutter.

        AOP is the source of many terms that are difficult to understand intuitively. Fortunately, you can write AOP modules as long as you understand three concepts. The three concepts are: advice, pointcut and advisor. Advice is code that you want to inject into different places inside another program. Pointcut defines the location where advice needs to be injected, usually a public method of a specific class. Advisor is an assembler for pointcut and advice, and is code that injects advice into a predefined location in the main program.

        Now that we know that we need to use advisors to inject "invisible" advice into the main code, let's implement a Spring AOP example. In this example, we will implement a before, which means that the code for the advice is executed before the called public method starts. The following is the implementation code of this before advice:

package song;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class TestBeforeAdvice implements MethodBeforeAdvice{

	@Override
	public void before(Method m, Object[] args, Object target)
			throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("Hello world!(by"+this.getClass().getName()+")");
	}
}

        The interface MethodBeforeAdvice has only one method that needs to be implemented before, which defines the implementation of advice. The before method shares three parameters, which provide quite a wealth of information. The parameter Method m is the method to be executed after the advice starts. The method name can be used as a condition to determine whether to execute the code. Object[] args is an array of arguments passed to the called public method. The parameter args and the name of the method being executed are useful information when logging is required. You can also change the arguments passed to m, but use this feature with care; the programmer who wrote the original main program was unaware that the main program might conflict with the arguments passed in. Object target is a reference to the object that executes method m. In the following BeanImpl class, advice is executed before each public method call:

package song;

public class BeanImpl implements Bean{

	@Override
	public void theMethod() {
		// TODO Auto-generated method stub
		System.out.println(this.getClass().getName()+"."
				+new Exception().getStackTrace()[0].getMethodName()
				+"() says HELLO!");
	}
}

        The class BeanImpl implements the following interface beans:

package song;

public interface Bean {
	
	public void theMethod();
}

        Although it is not mandatory to use an interface, programming towards an interface rather than an implementation is good programming practice and Spring encourages it. Pointcut and advice are implemented through configuration files, so next you just need to write the Java code of the main method:

package song;

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

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext ctx =
			new FileSystemXmlApplicationContext("springconfig.xml");
		
		Bean x = (Bean)ctx.getBean("bean");
		
		x.theMethod();
	}
}

        We'll start by reading in and processing the configuration file, and we're going to create it shortly. This configuration file will act as the "glue" to glue the different parts of the program together. After reading in and processing the configuration file, we get a creation factory ctx. Any object managed by Spring must be created through this factory. Objects can be used normally after they are created through the factory. The following configuration file assembles each part of the program:

<?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>song.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="song.BeanImpl"/>
 
 <!-- ADVISOR -->
 <bean id="theAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
  <property name="advice">
   <ref local="theBeforeAdvice"/>
  </property>
  <property name="pattern">
   <value>song.Bean.theMethod</value>
  </property>
 </bean>
 
 <!-- ADVICE -->
 <bean id="theBeforeAdvice" class="song.TestBeforeAdvice"/>
</beans>

        The order of the four bean definitions is not important. We now have an advice, an advisor containing the regular expression pointcut, a main program class and a configured interface that returns a reference to its own implementation through the factory ctx. Both BeanImpl and TestBeforeAdvice are direct configuration. We create a bean element with a unique ID and specify an implementation class.

        The advisor is implemented through a RegexMethodPointcutAdvisor class provided by the Spring framework. We use an attribute of advisor to specify the advice-bean it needs. The second attribute defines pointcut with regular expressions, ensuring good performance and readability. The last configuration is the bean, which can be created by a 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 behavior of this bean is defined by the following three properties:

  • The attribute proxyInterface defines the interface class. 
  • The attribute target points to a locally configured bean that returns an implementation of the interface. 
  • The property interceptorNames is the only property that allows defining a list of values. This list contains all advisors that need to be executed on the beanTarget. Note that the order of the advisor list is very important.

Second, Spring tools

        While you can manually modify Ant build scripts, using SpringUI makes Spring AOP as simple as a click of a mouse. You can install SpringUI as a plug-in of Eclipse. Then, you just right-click on your project and select "add Spring Project Nature". In the project properties, you can add Spring configuration files under "Spring Project". Add the following libraries to the project before compiling: aopalliance.jar, commons-logging.jar, jakarta-oro-2.0.7.jar and spring.jar.

 

3. Advantages and Disadvantages

        Spring has an advantage over other frameworks because it provides more functionality besides AOP. As a lightweight framework, it can play a role in different parts of J2EE. So even if you don't want to use Spring AOP, you probably still want to use Spring. Another advantage is that Spring does not require everyone on the development team to use it. Learning Spring should start from the first page of the Spring reference. The only downside to Spring is the lack of more documentation, but its mailing list is a nice addition, and more documentation is coming out constantly.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326703909&siteId=291194637
Recommended