The two core Spring AOP

The two core Spring AOP

AOP advantages:

  • Reduce the coupling between modules.
  • Make the system easier to extend.
  • Better code reuse.
  • Non-business code is more concentrated, not dispersed to facilitate unified management.
  • Business code more concise kept pure, it does not affect other doping code.

AOP is an addition to object-oriented programming, at runtime, the code dynamically cut into the specified class methods, programming ideas for the specified location is Oriented Programming. The same position of different methods into a section of the abstract object program is an object section of the AOP.

how to use?

  • Create Maven projects, pom.xml add
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.11.RELEASE</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.0.11.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.0.11.RELEASE</version>
    </dependency>
</dependencies>
  • Creating a calculator interface to Cal, the definition of four methods.
package com.southwind.utils;

public interface Cal {
    public int add(int num1,int num2);
    public int sub(int num1,int num2);
    public int mul(int num1,int num2);
    public int div(int num1,int num2);
}
  • Create a class that implements CalImpl interface.
package com.southwind.utils.impl;

import com.southwind.utils.Cal;

public class CalImpl implements Cal {
    public int add(int num1, int num2) {
        System.out.println("add方法的参数是["+num1+","+num2+"]");
        int result = num1+num2;
        System.out.println("add方法的结果是"+result);
        return result;
    }

    public int sub(int num1, int num2) {
        System.out.println("sub方法的参数是["+num1+","+num2+"]");
        int result = num1-num2;
        System.out.println("sub方法的结果是"+result);
        return result;
    }

    public int mul(int num1, int num2) {
        System.out.println("mul方法的参数是["+num1+","+num2+"]");
        int result = num1*num2;
        System.out.println("mul方法的结果是"+result);
        return result;
    }

    public int div(int num1, int num2) {
        System.out.println("div方法的参数是["+num1+","+num2+"]");
        int result = num1/num2;
        System.out.println("div方法的结果是"+result);
        return result;
    }
}

The above code, the coupling log information and business logic high, is not conducive to maintenance of the system, using AOP can be optimized, how to achieve AOP? Dynamic proxies manner.

Business code to find an agent, print log information of a job to pay the agent to do, so you just need to focus on the business code their own business can be.

package com.southwind.utils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class MyInvocationHandler implements InvocationHandler {
    //接收委托对象
    private Object object = null;

    //返回代理对象
    public Object bind(Object object){
        this.object = object;
        return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(method.getName()+"方法的参数是:"+ Arrays.toString(args));
        Object result = method.invoke(this.object,args);
        System.out.println(method.getName()+"的结果是"+result);
        return result;
    }
}

test

public class test1 {
    public static void main(String[] args){
        Cal cal = new CalImpl();
        MyInvocationHandler handler = new MyInvocationHandler();
        //注意Cal为接口
        Cal cal1 =(Cal) handler.bind(cal);
        cal1.add(1,2);
    }
}

The above is achieved by a dynamic proxy AOP process, more complex, difficult to understand, AOP Spring framework of the package, using the Spring Framework object-oriented thinking can be realized AOP.

Spring Framework of InvocationHandler need to create, only need to create a section object, all non-business code section can be completed in a subject, the Spring Framework underlying automatically cut a proxy object class and the class generation target according to.

LoggerAspect

package com.southwind.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class LoggerAspect {

    @Before(value = "execution(public int com.southwind.utils.impl.CalImpl.*(..))")
    public void before(JoinPoint joinPoint){
        //获取方法名
        String name = joinPoint.getSignature().getName();
        //获取参数
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println(name+"方法的参数是:"+ args);
    }

    @After(value = "execution(public int com.southwind.utils.impl.CalImpl.*(..))")
    public void after(JoinPoint joinPoint){
        //获取方法名
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"方法执行完毕");
    }

    @AfterReturning(value = "execution(public int com.southwind.utils.impl.CalImpl.*(..))",returning = "result")
    public void afterReturning(JoinPoint joinPoint,Object result){
        //获取方法名
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"方法的结果是"+result);
    }

    @AfterThrowing(value = "execution(public int com.southwind.utils.impl.CalImpl.*(..))",throwing = "exception")
    public void afterThrowing(JoinPoint joinPoint,Exception exception){
        //获取方法名
        String name = joinPoint.getSignature().getName();
        System.out.println(name+"方法抛出异常:"+exception);
    }

}

LoggerAspect class definition to add two notes at:

  • @Aspect: Indicates class is cut class.
  • @Component: The class of the object is injected into the IoC container.

The specific method to add notes at:

@Before: That specific location and time and method of execution.

CalImpl also need to add @Component, to the IoC container to manage.

package com.southwind.utils.impl;

import com.southwind.utils.Cal;
import org.springframework.stereotype.Component;

@Component
public class CalImpl implements Cal {
    public int add(int num1, int num2) {
        int result = num1+num2;
        return result;
    }

    public int sub(int num1, int num2) {
        int result = num1-num2;
        return result;
    }

    public int mul(int num1, int num2) {
        int result = num1*num2;
        return result;
    }

    public int div(int num1, int num2) {
        int result = num1/num2;
        return result;
    }
}

spring.xml configure AOP.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
">

    <!-- 自动扫描 -->
    <context:component-scan base-package="com.southwind"></context:component-scan>

    <!-- 是Aspect注解生效,为目标类自动生成代理对象 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

</beans>

context:component-scanThe com.southwindall classes in a package is scanned, if a class simultaneously added @Component, then scanned into IoC container such that it IoC managed object.

aop:aspectj-autoproxy Spring Framework's class and target class in conjunction with section automatically generate dynamic proxy objects.

  • Section: crosscutting concerns are modular abstract objects.
  • Notification: cut target to complete the work.
  • Target: Object to be notified, ie transverse to the object.
  • Agent: Object section after notification, the target mix.
  • The point of attachment: To insert the specific location service notification code.
  • Tangent point: AOP is positioned to the connection point through the tangent point.
Published 33 original articles · won praise 1 · views 2274

Guess you like

Origin blog.csdn.net/qq_40805620/article/details/104755406