Spring AOP module use

Table of Contents

1.JDK dynamic agent

2. Use the dynamic proxy in the AOP module in Spring

Five additional agent functions:

1. front

2. postposition

3. surround

4. exceptions

Configuration of applicationContext.xml

test

Three kinds of pointcut expressions:

1.execution

2.within

3.args

AOP is the abbreviation of Aspect Oriented Programming, which means: face-to-face programming, a technology to realize the unified maintenance of program functions through precompiling and dynamic agent during operation. AOP is OOP The continuation of Spring is not only a hot spot in software development, but also an important part of Spring framework

First, we use the native reflection in java to demonstrate the following dynamic proxy:

1.JDK dynamic agent

Let's say that there is now a class on the business side: UserServiceImpl.java

package org.example.service.impl;

import org.example.dao.UserDao;
import org.example.service.UserService;

public class UserServiceImpl implements UserService {
    private UserDao userDao;

    public UserServiceImpl() {
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void addUser() {
        System.out.println("Core functions...");
    }

    @Override
    public void play() {
        System.out.println("Hahaha, I'm also the core function...");
    }
}

One day, I suddenly want to add some new business logic to each method of this class. What should I do?

java can solve this problem by dynamic proxy through reflection:

@Test
    public void test2() {
        final UserService userService = new UserServiceImpl();
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("I'm an extra feature....");
                method.invoke(userService, args);
                System.out.println("I'm also an extra feature...");
                return null;
            }
        };
        UserService proxy = (UserService) Proxy.newProxyInstance(AppTest.class.getClassLoader(), userService.getClass().getInterfaces(), invocationHandler);
        proxy.addUser();
        System.out.println("##################");
        proxy.play();
    }

Operation result:

2. Use the dynamic proxy in the AOP module in Spring

It can be seen from the above demonstration that implementing dynamic proxy using Java has limitations and complexity, so Spring simplifies this in its AOP

Five additional agent functions:

1. front

package org.example.advice;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class BeforeAdvice implements MethodBeforeAdvice {
    /**
     * Topic logic, executed before core code
     *
     * @param method  Currently executing method object
     * @param objects Method parameters
     * @param o       Target object
     * @throws Throwable
     */
    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("i am method before" + method.getName() + "::args:" + objects.length + "  target" + o);
    }
}

2. postposition

package org.example.advice;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class AfterAdvice implements AfterReturningAdvice {
    /**
     * Execute after core function
     *
     * @param o       Core function return value
     * @param method  Method object
     * @param objects Parameter table of method
     * @param o1      Target object
     * @throws Throwable
     */
    @Override
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("i am method after:" + method.getName());
    }
}

3. surround

package org.example.advice;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class InterceptorAdvice implements MethodInterceptor {
    /**
     * @param methodInvocation
     * @return Core code execution results
     * @throws Throwable
     */
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("I'm on top of you...");
        Object proceed = methodInvocation.proceed();
        System.out.println("I'm under you...");
        return proceed;
    }
}

4. exceptions

package org.example.advice;


import org.springframework.aop.ThrowsAdvice;

public class ErrorAdvice implements ThrowsAdvice {
    public void afterThrowing(Exception e) {
        e.printStackTrace();
        System.out.println("Ah ah!!! Error");
    }
}

Configuration of applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
    dtd:document type definition
    xsd:xml schema definition
-->

<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userServiceImpl" class="org.example.service.impl.UserServiceImpl"/>
    <bean id="beforeAdvice" class="org.example.advice.BeforeAdvice"/>
    <!--Weave-->
    <aop:config>
        <!--        breakthrough point-->
        <aop:pointcut id="cutOne" expression="execution(* org.example.service.impl.UserServiceImpl.*(..))"/>
        <aop:pointcut id="cutOne2" expression="execution(* org.example.service.impl.UserServiceImpl.play(..))"/>

        <!--Weave an extra function into a specified entry point-->
        <aop:advisor advice-ref="beforeAdvice" pointcut-ref="cutOne"/>
    </aop:config>
    
</beans>

test

/**
     * AOP test
     */
    @Test
    public void test3() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
        //Use the target bean id to get the compiled object
        UserService userServiceImpl = applicationContext.getBean("userServiceImpl", UserService.class);
        userServiceImpl.play();
        System.out.println("#####################");
        userServiceImpl.addUser();
    }

Three kinds of pointcut expressions:

1.execution

<aop:pointcut id="cutOne" expression="execution(* org.example.service.impl.UserServiceImpl.*(..))"/>

2.within

Describe the package and class. All methods in the class cut in

<aop:pointcut id="pc" experssion="com.dao.impl.UserDaoServiceImpl"/>

3.args

Describe the parameter table, and cut in all the methods that meet the requirements

<aop:pointcut id="pc" experssion="args(int , String , com.entity.User)"/>

 

Thanks for watching!

 

69 original articles published, 88 praised, 10000 visitors+
Private letter follow

Tags: Spring Java xml JDK

Posted on Thu, 06 Feb 2020 07:53:48 -0500 by Invincible