Spring-AOP annotation-based implementation

1. AOP:

It is a complement to OOP programming. Translated as "Aspect Oriented Programming".

It can be understood as an interceptor framework, but this interceptor will be very arbitrary. If it intercepts a class, it will intercept all methods in this class. As a proxy to a target column, all methods of the target class are enhanced.

Two solutions:

1. Inelegant approach:

When adding enhancements, it is judged according to the method name whether to add enhancements, but in this way, the enhancement class has to be maintained all the time.

2. Facing the cut plane:

Combine the enhancement class with the interception condition, then configure this aspect into the ProxyFactory to generate the proxy.

Second, the relationship between AOP and aspects

1. Analogous to OOP and objects, AOP and aspects are such a relationship.

2. Aspects can also be seen as a tool of AOP.

3. Several concepts

Aspect (Advisor): is a term in AOP that represents cross-cutting logic separated from business logic, such as performance monitoring, logging, permission control, etc.

These functions can be extracted from the core business logic. The problem of code coupling can be solved, and the responsibilities are more single. Encapsulates enhancements and pointcuts.

Advice: A class that enhances the functionality of the code, cross-cutting into the code.

target: target method (JDK proxy) or target class (CGLIB proxy)

Proxy: JDK proxy, CGLIB proxy. Or through the ProxyFactory class production.

Pointcut: Match the class to be intercepted through a condition, which is called a pointcut. Such as intercepting all classes annotated with Controller. enhanced conditions.

Connection point: As the input parameter of the enhancement method, the information of the target method can be obtained.

Fourth, practice: customize an annotation, use Spring-AOP to implement business processing for the method of adding this annotation

1. The Spring jar package is introduced into the POM file, and other jars do not need to be referenced.

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>

2. Customize an annotation

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Monitor the progress of the request
 *   @author   wangfeixiong
  */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReviewProgressAnnotation {
    String value();
}

3. Configure Spring to enable AOP annotations

<?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:task="http://www.springframework.org/schema/task"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd ">

    <description>Spring MVC Configuration</description>

    <!-- Load configuration properties file --> 
    < context:property-placeholder ignore-unresolvable ="true" location ="classpath:*.properties" />
    
    <!-- Use Annotation to automatically register beans --> 
    < context:component-scan base-package ="com.future.dcwj" /> 
    <!-- Default annotation mapping support, org.springframework.web.servlet. mvc.method.annotation.RequestMappingHandlerMapping --> 
    < mvc:annotation-driven content-negotiation-manager ="contentNegotiationManager" > 
        < mvc:message-converters register-defaults ="true" > 
            <!-- Set the default encoding of StringHttpMessageConverter as UTF-8 --> 
            < bean class ="org.springframework.http.converter.StringHttpMessageConverter" >
                <constructor-arg value="UTF-8"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    
    <!-- Open the scheduled task in spring --> 
    < task:annotation-driven />
    
    <!--开始AOP-->
    <aop:aspectj-autoproxy/>    
    

    <!-- For access to static resource files, the path that cannot be mapped to the Controller will be handed over to the default servlet handler --> 
    < mvc:default-servlet-handler />

    <!-- Static resource mapping --> 
    < mvc:resources mapping ="/static/**" location ="/static/" cache-period ="31536000" />

    <!-- Define the path without Controller<->view direct mapping --> 
    < mvc:view-controller path = "/" view-name = "redirect:${web.view.index}" /> 
</ beans >

4. Write annotation classes and customize business

import com.future.dcwj.common.annotation.ReviewProgressAnnotation;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * describe:
 *
 * @author wangfeixiong
 * @date 2018/02/09
 */
@Component
@Aspect
public class ReviewProgressAOP {
    private final static Logger LOGGER = Logger.getLogger(ReviewProgressAOP.class);

    public static final String SUCESS = "true";
    private static final String NO_SUCESS = "false";
    public static final String  REVIEW_ACTION_PROGRESS= "reviewActionProgress";



    @Pointcut("@annotation(com.future.dcwj.common.annotation.ReviewProgressAnnotation)")
    public void pointcutName() {
    }


    /**
     * @param joinPoint
     */
    @Around("pointcutName()")
    public Object introcepter(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        ReviewProgressAnnotation progressAnnotation = methodSignature.getMethod().getAnnotation(ReviewProgressAnnotation.class);
        String operation = progressAnnotation.value();
        StringBuffer key = new StringBuffer();
        LOGGER.error(key.toString());
        User user = UserUtils.getUser();
        if (user != null) {
            key.append(user.getId());
        }
        key = key.append(operation);
        LOGGER.info(operation);
        try {
            Object result = joinPoint.proceed();
            map.put(key.toString(), SUCESS);
            JedisUtils.mapPut(REVIEW_ACTION_PROGRESS,map);
            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325158641&siteId=291194637