The content comes from: AOP technology understanding and use
1. What is AOP?
AOP technology is an aspect-oriented programming idea , which is added to enterprise development as a continuation idea of OOP (object-oriented programming), and is a programming idea proposed to make up for the defects in the OOP development process.
The bottom layer of AOP is also object-oriented; it's just that it is not oriented to ordinary Object objects, but to special AOP objects. The focus of AOP is the non-core general service modules (such as login check, etc.) that make up the system. Compared with ordinary objects, AOP does not need to provide functions through inheritance and method calls. It only needs to be referenced in the xml file. Reference non-core service functions to core business logic objects or methods that need to be modified. Finally realize the decoupling of objects. The ioc technology in spring realizes the decoupling between core business logic objects (such as LoginAction and DaoImpl), and the aop technology realizes the decoupling between core business logic objects and non-core general services (such as LoginAction and LoginCheckInterceptor).
2. What are the advantages of AOP over OOP?
The problem of OOP does not exist in the development phase. In the development phase and the first test phase, using OOP is the most efficient and easiest way. The OOP problem is reflected in the secondary testing stage after the software development is completed. After the software is modified, the modified method in the software needs to be re-tested before it can be run online. At this point the test object is the currently modified method and all other methods that have a cascade/dependency with this method. Doing so obviously prolongs the secondary test period. When using aop in the secondary test, because it is configured in the xml file, it is not necessary to test all related classes.
3. How to use aop in spring?
We use an example to introduce how to use aop in spring.
Here we provide a class StuAction to add the function of login checking to the core business logic methods (addStu, delStu) in this class.
public class StuAction { public String addStu(){ System.out.println( "Process the addStu.action request submitted by the client" ); // int i = 1/0; return "success" ; } public String delStu () { System.out.println( "Process the selStu.action request submitted by the client" ); return "success" ; } }
AOP technology in spring provides four basic types of notifications:
- before notification~ Notification MethodBeforeAdvice before core method execution
- after notification~ The notification AfterReturningAdvice after the core method is executed
- Around notification~ The notification before+after filter and interceptor when the core method is executed is a kind of around notification MethodInterceptor
- Throws notification~ Notification ThrowsAdvice executed after an exception occurs in the execution of the core method
Let's test these four notifications:
Note: Uncomment the StuAction when testing the athrows notification, int i = 1/0;
and we create an exception for testing.
In addition, after notification is mainly used to output logs after the core method call ends, so log4j is used here.
// Define a notification class that implements MethodBeforeAdvice - before notification public class LoginCheckAdvice implements MethodBeforeAdvice { // This method will be automatically executed before the core method is executed @Override public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable { System.out.println( "Determine whether there is currently a logged in user" ); // According to the result of the judgment, decide whether to execute the subsequent core method } } // after notification public class LoggerAdvice implements AfterReturningAdvice { private static Logger logger = Logger.getLogger(LoggerAdvice.class ); // This method will be automatically executed after the core method is executed @Override public void afterReturning(Object arg0, Method arg1, Object [] arg2, Object arg3) throws Throwable { // TODO Auto-generated method stub System.out.println("Logging after the core method is executed" ); // Record a log message logger.error("This is an error level log message" ); logger.warn( "This is a warning level log message" ); logger.info( "This is an info level log message" ); logger.debug( "This is a debug level log message" ); } } // around通知 public class AroundAdvice implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { // struts2 interceptor ActionInvocation dispatcher System.out.println("around notification-before core method execution" ); Object result = invocation.proceed(); // Transfer the requested execution permission to the core business logic method addStu/selStu // result - the execution result of the core method addStu()/selStu() System.out.println("result- -"+result); // success System.out.println("around advice - after the core method is executed" ); return result; } } // throws notification public class ExceptionAdvice implements ThrowsAdvice { // This method will be automatically executed after the core method execution exception public void afterThrowing(Method method, Object[] args, Object target, Exception ex){ System.out.println( "An exception occurred in the execution of the core method... Exception message"+ ex.getMessage()); } }
log4j.properties
log4j.rootLogger = info , etoak1, etoak2 log4j.appender.etoak1=org.apache.log4j.ConsoleAppender log4j.appender.etoak1.layout=org.apache.log4j.TTCCLayout log4j.appender.etoak2=org.apache.log4j.FileAppender log4j.appender.etoak2.file=C://log4j.html log4j.appender.etoak2.layout=org.apache.log4j.HTMLLayout
Well, the preparations are done, so how do we configure aop in the spring container?
Here comes the point!
Configure aop in applicationContext.xml:
first import all packages under aop in spring, log4j package
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd"> <!-- Introduce aop namespace, schame file Requirements: Use the AOP technology provided by spring for Add accessibility to login check 1 Encapsulate the function of login check into an AOP component in spring AOP component [struts2 interceptor filter filter spring notification] 2 will notify classes, core business logic objects [two objects with dependencies] Configured in the ioc container --> <bean id="action" class="com.etoak.action.StuAction"/> <bean id="lc" class="com.etoak.util.LoginCheckAdvice"/> <bean id="logger" class="com.etoak.util.LoggerAdvice"/> <bean id="around" class="com.etoak.util.AroundAdvice"/> <bean id="exce" class="com.etoak.util.ExceptionAdvice"></bean> <!-- 3 Use AOP to reference the notification class to the business logic object aop:config : configure an aop component [how to use the notification class] 3.1 Describe who needs to refer to the functions provided by this notification class aop:pointcut configures the pointcut entry point: used to describe where the notification executes [where executes] Address: around which method/methods to execute The pointcut points to a set of methods that need to add login checking functionality expression attribute (expression): notify the execution of an expression, using the execution result of the expression as the entry point The execution result of the expression also points to a set of methods execution(* com.etoak.action.*.*(..)) execution(1 2) The content of the expression in execute() 1 used to qualify the return value of the method * 2 The location and name used to qualify the method com.etoak.action.*.*(..) 3.2 Assemble notification class + pointcut to form an AOP component [Aspect] --> < aop:config > < aop:pointcut expression ="execution(* com.etoak.action.Stu*.add*(..)) || execution(* com.etoak.action.*.del*( ..))" id ="pc" /> < aop:advisor advice-ref ="lc" pointcut-ref ="pc" /> <!-- Refer the function provided by the advice class id="lc" to The set of methods to which the pointcut id="pc" points. --> < aop:advisor advice-ref ="logger" pointcut-ref ="pc" /> < aop:advisor advice-ref ="around" pointcut-ref="pc"/> <aop:advisor advice-ref="exce" pointcut-ref="pc"/> </aop:config> </beans>
Use the test class to test it:
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); StuAction la = (StuAction)ac.getBean("action"); la.addStu (); la.delStu (); } }
The result is as follows: