SpringAOP Entry Point Specification and Realization of Obtaining Method Parameters

  • 2021-09-20 20:25:59
  • OfStack

Entry point specification


@Pointcut("execution(* com.example.server.service.TeacherService.*(..))")

The above entry point cuts into all the methods below com. example. server. service. TeacherService.

Let's introduce the specification of pointcut expression under 1 in detail.

1. execution (): The body of the expression.

2. Position 1: Represents the return type, and * indicates all types.

3. Position 2: Indicates the package name, class name and method name (method parameter) to be intercepted.

It should be noted that it must be a full class name. Where you can use * to denote all packages.

For example: com. example. server. service. Represents all classes under the service package; com. example. server.. represents all packages and all their classes under the server package.

You can specify a certain 1 method, or you can use it to represent all the methods of the class (satisfy the previous return type)

Again, parameters can be concrete, such as: (int, String), or arbitrary parameters can be represented by (..). (Only methods with matching parameters can be cut in)

Obtaining Method Parameters in AOP


"execution(* com.example.server.service.TeacherService.uploadExperience(..)) && args(userId)"

As you can see, one change is added to the above expression, so that we can get the parameter when cutting into the method call in AOP, so that we can use this parameter in AOP method.

Here is an example:


    @After("execution(* com.example.server.service.TeacherService.uploadExperience(..)) && args(userId)")
    public void updateLevel(Long userId){
  // Code block, you can now use it in the code block userId
    }

AOP gets the parameters of session

Sometimes it is necessary to use the values previously stored in session in AOP. In fact, this is also very simple.


ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpSession session = attr.getRequest().getSession(true);
long userId = (long) session.getAttribute(USER_ID);

Similarly, we can also obtain request and response through ServletRequestAttributes


HttpServletResponse response = attr.getResponse();
HttpServletRequest request = attr.getRequest();

SpringAOP: Gets parameters for pointcut comments

spring aop How to Obtain Parameters, Method Names, Return Values, Exceptions and Other Information of Entry Point Related Methods in Section Class

The idea of aop can help us decouple the code well. For example, as we mentioned earlier, the log code is completely independent of the business layer code and integrated through the proxy class of spring aop. In the section class, we can also get the relevant information of the original entry point through the interface provided by spring.

First of all, let's start with the code

Business layer code StudentServiceImpl


@Service("studentService")
public class StudentServiceImpl implements StudentService {
    @Override
    public int addStudent(Student student) throws Exception {
            System.out.println("addStudent... Business layer code execution ...");
            return 1;
    }
    @Override
    public int deleteStudent(Integer id) throws Exception{
            System.out.println("deleteStudent... Business layer code execution ...");
            int i = 1/0;
            return 0;
    }
}

Section class StudentServiceLogger


@Aspect
@Component
public class StudentServiceLogger {
    @Before("execution(* com.wuwl.service.impl.StudentServiceImpl.*(..) )")
    public void doBefore(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName+" Before executing the method ...");
        System.out.println(" The parameters are: "+ Arrays.asList(args));
    }

    @After("execution(* com.wuwl.service.impl.StudentServiceImpl.*(..) )")
    public void doAfter(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName+" Method is executed ...");
    }

    @AfterReturning(value = "execution(* com.wuwl.service.impl.StudentServiceImpl.*(..) )" , returning = "returning")
    public void doReturn(JoinPoint joinPoint,Object returning){
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName+" Method with a return value of :"+returning);
    }

    @AfterThrowing(value = "execution(* com.wuwl.service.impl.StudentServiceImpl.*(..) )",throwing = "ex")
    public void doThrow(JoinPoint joinPoint,Exception ex){
        String methodName = joinPoint.getSignature().getName();
        System.out.println(methodName+" Method exception, the exception information is: "+ex.getMessage());
    }
}

Test class AopTest


public class AopTest {
    ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    @Test
    public void test1() throws Exception {
        StudentService studentService = ac.getBean("studentService",StudentService.class);
        studentService.addStudent(new Student());
        System.out.println("================== Cut ===============");
        studentService.deleteStudent(1);
    }
}

Finally, the log output

Before the addStudent method executes...
The parameters are: [com. wuwl. domain. Student @ 7e5c856f]
addStudent... Business tier code execution...
After the addStudent method is executed...
The addStudent method returns with a return value of 1
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
Before the deleteStudent method executes...
Parameters are: [1]
deleteStudent... Business tier code execution...
After the deleteStudent method is executed...
deleteStudent method exception, exception message:/by zero

Regarding the relevant information of the breakthrough point method, spring is well encapsulated in org. aspectj. lang. JoinPoint interface. It should be noted here that there is also an interface named like this under org. aopalliance. intercept package, so don't make a mistake.

joinPoint. getArgs () method can return the parameter information of the cut-in method, and the return value is an array, which can be obtained by traversing; The return value of the joinPoint. getSignature () method is the method signature, and the signature interface includes information such as the method name.

If you need to get the return value of the cut-in method or exception information in the notification method, you need to use the corresponding attribute of the corresponding annotation.

Click on the @ AfterReturning annotation to see an String returning () default ""; Attribute, add the return value parameter in the notification method, and then declare the parameter as the return value of the cut-in method in the annotation. The operation method can refer to the above code.

Similarly, use String throwing () default "" annotated by @ AfterThrowing; Property, you can get the exception information thrown by the cut-in method.


Related articles: