AOP aspect oriented programming

AOP introduction

AOP(Aspect Oriented Progrmming) is a technology of aspect oriented programming, which realizes the unified maintenance of functions through precompiled mode and dynamic agent during operation.

Role of Aop

  1. While the program is running, it enhances the function of the program without modifying the code.
  2. Make the essential public functions into aspects, and cut into the code to run with the program.
  3. When writing business, we only focus on core functions, reduce the coding burden and focus more on business.

AOP terminology

  • Join point: a specific location where a program executes, such as a class with two methods, both of which are join points.
  • Pointcut; Each program class has multiple connection points, and AOP locates specific connection points through pointcuts. The join point is equivalent to the record in the database. The entry point is the query condition. A cut point can match multiple join points. The pointcut defines where to do it.
  • Advice: a notification is a piece of code woven into the target connection point. In Spring, in addition to describing a piece of code, notifications also have another information related to connection points, that is, execution point orientation. Combining the execution point orientation information and tangent point information, we can find a specific connection point. Notifications define what needs to be done and when to do it at a connection point.
  • The Spring aspect can apply five types of notifications
  1. Pre notification (Before): calling the notification function before the target method is invoked.
  2. Pre notification (After): calling the notification function before the target method is invoked.
  3. Return notification (After-returning): call notification after the method has been successfully executed.
  4. Exception notification (After-throwing): calling notification after the target method throws an exception.
  5. Surround notification: the notification wraps the notified method and executes custom behavior before and after the notified method is called. The input parameter value can be modified around the notification
  • Aspect: the aspect consists of pointcuts and notifications. It includes both the definition of crosscutting logic and the definition of connection points. Spring AOP is the framework responsible for implementing the aspect, which weaves the crosscutting logic defined by the aspect into the connection point specified by the aspect.
  • Aspect is the combination of pointcut notifications. Aspect knows all the things it needs to do: when, where and what to do
  • Target object: that is, the object to be enhanced, and the notification logic is woven into the target class. Without AOP, the target business class needs to implement all logic by itself. With the help of AOP, the target business class only implements the program logic of non crosscutting logic, while the crosscutting logic such as performance monitoring and transaction management can be dynamically woven into a specific connection point using AOP
  • Weaving: weaving is the process of adding notifications to the specific connection points of the target class. AOP is like a loom that seamlessly weaves together target classes, notifications or introductions through AOP. According to different implementation technologies, AOP can be woven in three ways:
  1. Compile time weaving, which requires the use of a special Java compiler
  2. Class loading period weaving, which requires the use of special class loaders
  3. Dynamic proxy weaving is used to add notification generation subclasses for the target class at run time
  • Weaving is the process of applying the aspect to the target object to create a new proxy object. Spring uses dynamic proxy weaving, while AspectJ uses compilation time weaving and class loading time weaving
  • Proxy: after a class is woven into the notification by AOP, a result class is generated. It is a proxy class that combines the original class and notification logic. According to different proxy methods, the proxy class may be either a class with the same interface as the original class or a subclass of the original class, so we can call the proxy class in the same way as calling the original class

Implementing AOP with annotations

Common notes:

@The Aspect is configured on the Aspect class

@PointCut("expression") configures the pointcut and adds it to the method

@Before configuring the pre notification method

@After configure post notification method

@Around configure surround notification method

@AfterReturning configures the post return value notification method

@AfterThrowing configures the post throw exception notification method

Example: use AOP to complete the log tracking of all methods in the service layer. The log can output the current method name, the passed in parameter value, and the execution time (using surround)

Guide Package:

  1. spring-context
  2. spring-aop
  3. spring-test
  4. aspectjrt
  5. aspectjweaver
  6. junit

Configuration class:

SpringConfig.java

//Configuration class annotation
@Configurable
//Package scan annotation
@ComponentScan(basePackages = "cn.blb.aop")
//Power on aop annotation
@EnableAspectJAutoProxy
public class SpringConfig {

}

User service interface:

UserService.java

//User service interface
public interface UserService {
    //Method 1
    public String updateMoney(String name,double money);

    //Method 2
    public String updateMoney2(String name);
}

Implement user service interface:

UserServiceImpl.java

//spring Service layer annotation
@Service
//Implement user service interface
public class UserServiceImpl implements UserService {
    @Override
    public String updateMoney(String name, double money) {
        System.out.println("I to"+name+"transfer accounts"+money);
        return name;
    }

    @Override
    public String updateMoney2(String name) {
        System.out.println("I to"+name+"transfer accounts");
        return name;
    }
}

Added features:

 UserLogService.java

//Configure section
@Aspect
@Component
public class UserLogService {
    //Configure tangent point
    @Pointcut("execution(* cn.blb.aop..*.*(..))")
    public void pointcut() {
    }

    //Use notification wrap
    @Around("pointcut()")
    public void getLog(ProceedingJoinPoint proceedingJoinPoint) {
        //Get method name
        String name = proceedingJoinPoint.getSignature().getName();
        System.out.println("Method name:"+name);
        //Get passed in parameters
        Object[] args = proceedingJoinPoint.getArgs();
        System.out.println("The parameters passed in are:");
        for (Object a : args) {
            System.out.println(a);
        }
        //Get current time
        Date data = new Date();
        //set time format
        SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = form.format(data);
        System.out.println("execution time" + time);
        try {
            //Call enhanced method
            proceedingJoinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

}

 

It is worth mentioning that the input parameter value can be modified by surrounding notification

When the enhanced method is called, another processed (new object [] {parameter value}) is called

Test class:

Test.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class testUserService {

    //Spring Auto assembly annotation for
    @Autowired
    private UserService userService;
    
    @Test
    public void testService(){
        userService.updateMoney("Zhang Shan",2000D);
        userService.updateMoney2("Li Si");
    }
}

Operation results:

 

Keywords: Spring

Added by ProXy_ on Sat, 22 Jan 2022 01:18:48 +0200