What is the AOP

AOP(Aspect Oriented Programming) means: section-oriented Programming, through pre-compilation and runtime dynamic proxy to achieve unified maintenance of program functions of a technology. AOP is a continuation of OOP, a hot topic in software development, an important part of the Spring framework, and a derivative paradigm of functional programming. Using AOP, each part of the business logic can be isolated, thus reducing the degree of coupling between each part of the business logic, improving the reusability of the program, and improving the efficiency of development.

Aop’s role in Spring

Provide declarative transactions; Allows user – defined facets

  • Crosscutting concerns: Methods or functions that span multiple modules of an application. That is, the part that is irrelevant to our business logic, but that we need to focus on, is crosscutting concerns. Such as logging, security, caching, transactions and more….
  • ASPECT: A special object whose crosscutting concerns are modularized. That is, it is a class.
  • Advice: Work that must be done by the aspect. That is, it is a method in a class.
  • Target: indicates the notified object.
  • Proxy: Object created after notification is applied to the target object.
  • PointCut: The definition of the “place” where a tangent notification is executed.
  • Join Point: The execution point that matches the pointcut.

In SpringAOP, crosscutting logic is defined through Advice, and there are five types of Advice supported in Spring:That is, Aop adds new functionality without changing the original code.

Use Spring to implement Aop

Using AOP requires importing dependency packages

<! -- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
  <groupId>org.aspectj</groupId>
  <artifactId>aspectjweaver</artifactId>
  <version>1.9.6</version>
</dependency>
Copy the code

The first way

Write the business interfaces and implementation classes through the SpringAPI implementation

public interface UserService {
    String add(a);
    void del(a);
    void upd(a);
    void qry(a);
}
Copy the code
public class UserServiceImpl implements UserService {
    @Override
    public String add(a) {
        System.out.println("add...");
        return "add...";
    }

    @Override
    public void del(a) {
        System.out.println("del...");
    }

    @Override
    public void upd(a) {
        System.out.println("upd...");
    }

    @Override
    public void qry(a) {
        System.out.println("qry..."); }}Copy the code

Write the enhancement class pre-enhancement

import java.lang.reflect.Method;

public class LogBefore implements MethodBeforeAdvice {
    / * * *@paramMethod Specifies the method of the target object to execute@param* args parameter@paramTarget Target object *@throws Throwable
     */
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName() + "The" + method.getName() + "Executed!"); }}Copy the code

The rear enhancement

import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;

public class LogAfter implements AfterReturningAdvice {
	/ * * *@paramReturnValue the returnValue of the target object method *@paramMethod Specifies the method of the target object to execute@param* args parameter@paramTarget Target object *@throws Throwable
     */
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println(target.getClass().getName() + "The" + method.getName() + "Executed, returns :"+ returnValue); }}Copy the code

Finally go to the spring file registration, and implement AOP cut implementation, pay attention to import constraints


      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<! Registered bean -- -- -- >
    <bean id="userService" class="com.circle.service.impl.UserServiceImpl"/>
    <bean id="before" class="com.circle.log.LogBefore"/>
    <bean id="after" class="com.circle.log.LogAfter"/>

    <aop:config>
	<! Configure pointcut expressions -->
        <aop:pointcut id="pointcut" expression="execution(* com.circle.service.*.*(..) )"/>
	<! -- Implementation surround; Advice-ref execute method.pointcut-ref pointcut -->
<! -- Method before -->
        <aop:advisor advice-ref="before" pointcut-ref="pointcut"/>
<! -- Method after -->
        <aop:advisor advice-ref="after" pointcut-ref="pointcut"/>
    </aop:config>
    
</beans>
Copy the code

test

public class MyTest {

    @Test
    public void test01(a){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService service = context.getBean("userService", UserService.class); service.add(); service.del(); service.upd(); service.qry(); }}Copy the code

Features: No need to change the original code. Combine the new business with the old business to realize the reuse of the old business


The second way

Custom cut classes

public class DiyLog {
    public void before(a){
        System.out.println("====before====");
    }

    public void after(a){
        System.out.println("====after===="); }}Copy the code

The Spring configuration


      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<! Registered bean -- -- -- >
    <bean id="userService" class="com.circle.service.impl.UserServiceImpl"/>
    <bean id="before" class="com.circle.log.LogBefore"/>
    <bean id="after" class="com.circle.log.LogAfter"/>
<! -- Custom entry class -->
    <bean id="divLog" class="com.circle.log.DiyLog"/>
<! Aop configuration -->
    <aop:config>
<! -- Define the section -->
        <aop:aspect ref="divLog">
	<! Configure pointcut expressions -->
            <aop:pointcut id="pc" expression="execution(* com.circle.service.*.*(..) )"/>
            <aop:before method="before" pointcut-ref="pc"/>
            <aop:after method="after" pointcut-ref="pc"/>
        </aop:aspect>
    </aop:config>
    
</beans>
Copy the code

Test code same as above…


The third way

Write an annotation entry class using an annotation implementation

// Implement AOP using annotations
@Aspect// indicate that this class is an aspect
public class AnnotationPointCut {
    private final String pointcut = "execution(* com.circle.service.impl.*.*(..) )";

    @Before(pointcut)
    public void before(a){
        System.out.println("before... - - - + + +");
    }

    @After(pointcut)
    public void after(a){
        System.out.println("after... - - - + + +");
    }

    @Around(pointcut)
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Around the front...");
// Execute method
        joinPoint.proceed();
        System.out.println("Around the back..."); }}Copy the code

The Spring configuration


      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<! Registered bean -- -- -- >
    <bean id="userService" class="com.circle.service.impl.UserServiceImpl"/>
    <bean id="pointCut" class="com.circle.log.AnnotationPointCut"/>
<! -- Enable annotation support -->
    <aop:aspectj-autoproxy/>
</beans>
Copy the code

Test code same as above…