AOP of SSM spring (XML + annotation)

Time:2021-10-24

AOP of SSM spring (XML + annotation)

AOP is the abbreviation of aspect oriented programming, which means that aspect oriented programming is a technology to realize the unified maintenance of program functions through precompiled mode and dynamic agent during operation.

Main function application scenarios: logging, performance statistics, security control, transaction processing, exception handling, etc. Divide the code of these scenarios from the business logic code,

POM dependency

Whether it is configuration or annotation, you need to add the following dependencies in the POM file:

org.aspectj
    aspectjweaver
    1.9.7

Configure and implement AOP

Now suppose there is such a scenario: Service login – > conduct various business scenarios – > Service exit login. The following is a simple implementation of this scenario:

Basic implementation:

  1. Write a service:
  2. public interface UserService {
        void login(String token);
        void logout();
    }
  3. Write a service implementation class:
  4. public class UserServiceImpl implements UserService {
        @Override
        public void login(String token) {
            System. Out. Println ("execute login: login succeeded \ ttoken:" + token);
        }
        @Override
        public void logout() {
            System.out.println ("log out");
        }
    }
  5. Add bean configuration:
  6. Write test code:
  7. public class AopTest {
        @Test
        public void test() {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            UserService userService = (UserService) context.getBean("userService");
            userService.login("123");
            System. Out. Println ("simulate various business scenarios...);
            userService.logout();
        }
    }
  8. View run results:
  9. AOP of SSM spring (XML + annotation)

The simple scenario implementation has been completed. Now suppose the project manager says that it is necessary to add log collection for login and logout to see how many users have logged in every day. Now some students may think of adding log code to the login and logout interface,

AOP injection to the specified business method:

  1. Implementation method of writing log:
  2. public class Log {
        public void logBefore() {
            System. Out. Println ("annotation log: ========= injection before business method execution ======== (before)");
        }
        public void logAfter() {
            System. Out. Println ("annotation log: ======== injection after business method execution ======== (after)");
        }
    }
  3. For the XML configuration related to AOP, the annotation explains the meaning of each attribute:
  4. AOP of SSM spring (XML + annotation)

  5. Run the above test code again:
  6. AOP of SSM spring (XML + annotation)
    By comparing the results of the two runs, it can be found that the second AOP log injection was successfully completed without changing the business code implementation logic.

AOP injection into multiple business methods:

  1. For the XML configuration related to AOP, the annotation explains the meaning of each attribute:
  2. AOP of SSM spring (XML + annotation)

  3. Run the above test code for the third time:
  4. AOP of SSM spring (XML + annotation)
    Compared with the last run, it can be found that this time not only logs are injected before and after login logic, but also logs are injected after exiting login.

Surround interception of AOP injection

The previous two injection methods can implement the injection log before and after multiple business method logics. The limitation of before and after notifications is that they cannot obtain business parameters or intercept and block business method logics.around

  1. Write the validation implementation to be injected:
  2. public class Verify {
        public void check(ProceedingJoinPoint joinPoint) throws Throwable {
            Object[] args = joinPoint.getArgs();
            if (args == null || !(args[0] instanceof String) || args[0].toString().length() < 5) {
                System. Out. Println ("login exception: invalid token");
            } else {
                //1. In the surrounding notification scenario, if and only if this method is called, subsequent notifications and business logic will continue to execute. Otherwise, subsequent notifications and business logic will be blocked and intercepted.
                //2. If the parameter proceedingjoinpoint is not added to the method entry, subsequent notifications and business logic will be blocked and intercepted by default.
                joinPoint.proceed();
            }
        }
    }

    Note about the proceedingjoinpoint object:

  • This object can only notify the scene in around;
  • If this parameter object is not added to the injection method, the subsequent notification and business method logic will be blocked;
  • If this parameter object is added to the injection method, but the process () method of the object is not called in the method, the interception of subsequent notifications and business method logic will also be blocked;
  • Business method parameter values can be obtained from this object;
  • To block subsequent notifications, you must configure the around notification in AOP configuration to execute in order before other notifications, otherwise it will be invalid.
  • Write AOP configuration:
  • AOP of SSM spring (XML + annotation)

  • Scenario test with token length > = 5:
  • public class AopTest {
        @Test
        public void test() {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            UserService userService = (UserService) context.getBean("userService");
            userService.login("12345");
        }
    }

    This scenario will go to the else logic of the check method. After executing joinpoint. Processed(), the business method can log in normally:
    AOP of SSM spring (XML + annotation)

  • Scenario test with token length < 5:
  • public class AopTest {
        @Test
        public void test() {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            UserService userService = (UserService) context.getBean("userService");
            userService.login("123");
        }
    }

    This scenario does not execute joinpoint. Proceed (), so the login business logic will be blocked:
    AOP of SSM spring (XML + annotation)Notes for note injection:

    1. If multiple sections are configured, they are executed in sequence;
    2. The surround notification will only block the notification configured behind it, and the notification in front of it will be injected normally.

    Implementing AOP with pure annotations

    The above has realized code injection through configuration without changing the business logic code. In addition to using configuration to implement AOP, you can also use a simpler annotation method.

    1. In the spring configuration file, add a line of configuration to enable AOP to support annotations:
    2. Write cut class:
    3. //@Aspect: aspect annotation
      @Aspect
      public class AnnotationLog {
          //@Before: pre notification, the same as configuration - AOP: before
          @Before("execution(* com.zx.demo.spring..*(..))")
          public void logBefore() {
              System.out.println ("log: before operation");
          }
          //@Logafter: pre notification, the same as configuration - AOP: after
          @After("execution(* com.zx.demo.spring..*(..))")
          public void logAfter() {
              System.out.println ("log: after operation");
          }
          //@Around: pre notification, the same as configuring - AOP: around
          @Around("execution(* com.zx.demo.spring..*(..))")
          public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
              System. Out. Println ("business parameters obtained:" + joinpoint. Getargs() [0]);
              System. Out. Println ("surround notification start");
              joinPoint.proceed();
              System. Out. Println ("end of surround notification");
          }
      }
    4. Run test code:
    5. AOP of SSM spring (XML + annotation)
      It can be seen that annotation implements aspect injection more simply, and the execution order of annotation notification is: surround Notification – > pre Notification – >Business method->Post notification.


    The configuration and annotation methods can realize the aspect code injection. After the spring boot, the introduction annotation method is more used.