A new colleague asked me, what is Spring AOP aspect-oriented programming? After my operation, he said to invite me to dinner!

Spring AOP aspect-oriented programming

AOP (aspect-oriented programming), one of the three core ideas in Spring:

In the software industry, AOP is the abbreviation of Aspect Oriented Programming, which means: aspect-oriented programming, a technology that realizes unified maintenance of program functions through pre-compilation and runtime dynamic proxy. AOP is a continuation of OOP, a hot spot in software development, an important content in the Spring framework, and a derivative paradigm of functional programming. AOP can be used to isolate various parts of the business logic, thereby reducing the coupling degree between the various parts of the business logic, improving the reusability of the program, and improving the efficiency of development at the same time. A technology that achieves unified maintenance of program functions through pre-compilation and runtime dynamic proxy.

(For more in-depth please Baidu)

Spring 2.0 has greatly improved AOP. First of all, the configuration of AOP XML is simpler. Spring 2.0 introduces a new mode, which supports the definition of aspects developed from regular Java objects, makes full use of the AspectJ entry point language, and provides a complete type of Advice (that is, there is no redundant conversion and Object[] parameter manipulation). In addition, proud of the development of Annotation, Spring 2.0 provides support for @AspectJ aspects, which can be shared between AspectJ and Spring AOP, requiring only simple configuration.

AOP mechanism? 【Data Acquisition】

Using AOP still needs to modify all methods, but the process of modifying this method is done by Spring for us

AOP notification type:

  Pre-notification, keyword before. Refers to notification before a method is executed.

   Post notification, keyword after. Refers to notification after a method is executed.

   Surround notification, keyword around. The value is to notify before and after a method is executed.

   Notify after an exception is thrown, throw. After a method is in progress and an exception is thrown for notification.

Operation code record:

<?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: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-4.2.xsd">
    <!-- 定义bean -->
    <bean id="stuService" class="com.lxit.aop.service.StudentService" />
    <!-- AOP配置 -->
    <!-- 添加Aspect的bean -->
    <bean id="logAspect" class="com.lxit.aop.aspect.LogAspect" />
    <aop:config>
        <!-- 定义一个pointcut -->
        <aop:pointcut id="servicepointcut" 
        expression="execution(* com.lxit.aop.service.*.*(..))" />
        <!-- 定义aspect,引用生成的aspectBean 并指定pointcut 和 method-->
        <aop:aspect id="aspect1" ref="logAspect">
            <aop:after pointcut-ref="servicepointcut" method="logAdd" />
        </aop:aspect>
    </aop:config>
</beans>
public static void main(String[] args) {
ApplicationContext ac = 
    new ClassPathXmlApplicationContext("spring.xml");
StudentService service = (StudentService) ac.getBean("stuService");
service.add();
service.getStudent();
}

Exception throwing enhancements:

The feature of exception throwing enhancement is to weave enhanced processing when the target method throws an exception,
but exception handling generally requires obtaining exception parameters.
Add the aspect of exception handling in the configuration file.
Use <aop:after-throwing for exception weaving.

public class ExceptionAspect {
public void exceptionLog(Exception e){
    System.out.println("发生异常,写入日志。" + e.getMessage());
}
}
<bean id="exceptionAspect" class="com.lxit.aop.aspect.ExceptionAspect" />
<aop:config>
<!-- 定义一个pointcut -->
<aop:pointcut id="servicepointcut" 
    expression="execution(* com.lxit.aop.service.*.*(..))" />
<!-- 定义aspect,引用生成的aspectBean 并指定pointcut 和 method-->
<aop:aspect id="aspect2" ref="exceptionAspect">
    <!-- 表示当程序发生异常后才织入 -->
    <aop:after-throwing method="exceptionLog" 
         pointcut-ref="servicepointcut" throwing="e"/>
</aop:aspect>
</aop:config>

Surround Enhancement:

Surround enhancement can be woven into enhancement processing before and after the target method.
Surround enhancement is the most powerful enhancement processing. Spring gives it all the control of the target method.
In the surround enhancement processing, the parameters of the target method can be obtained or modified. , the return value, which can be handled abnormally, and can even determine whether the target method is executed

public class AroundLogger {
    public Object aroundLogger(ProceedingJoinPoint jp) throws Throwable { … } 
}
<bean id="theLogger" class="aop. AroundLogger"></bean>
<aop:config>
    <aop:pointcut id="pointcut" expression="execution(* biz.IUserBiz.*(..))" />
    <aop:aspect ref="theLogger">
        <aop:around  method="aroundLogger"  pointcut-ref="pointcut" />
    </aop:aspect>
</aop:config>

The difference between the five weaving methods:


<aop:before ...>: weaves in before the target method is called.
As long as the before method is executed, the target method will always be called, but before can prevent the execution of the target method by throwing an exception, and before cannot access the return value of the target method.

<aop:after…>: Weaves in after the target method call.
After cannot organize the execution of the target method, and after cannot access the return value of the target method.

<aop:after-throwing..>: Weaving in when an exception is thrown. If throwing is specified, an exception parameter must be specified, the enhanced method must have the same name as this parameter, and the type must be greater than the exception type.

<aop:after-returning…>: Weaves in after the target method has successfully executed.
after-returning: The execution of the target method cannot be prevented, and the return value of the target method can be accessed, but cannot be modified.

<aop:around…>: Weaves in before and after the target method call. Its processing method must contain a ProceedingJoinPoint parameter.
aop:around: can organize the execution of the target method, can access the return value of the target method, and can modify the return value.
All of the above enhancers can specify args to specify parameters

A good effect can be seen in Struts2, hibernate, and Spring integration.

It is a typical case to define a pointcut in the serivce layer to start a series of operations before executing the operation, such as writing logs, transactions and other operations.

AOP usage scenarios [data acquisition]

AOP is used to encapsulate cross-cutting concerns, which can be used in the following scenarios:

Authentication permission Caching cache Context passing content delivery Error handling error handling Lazy loading lazy loading

Debugging debugging logging, tracing, profiling and monitoring recording tracking optimization calibration Performance optimization performance optimization

Persistence Persistence Resource pooling Synchronization Synchronization Transactions

Thanks for reading, attention + triple is the biggest support!

Guess you like

Origin blog.csdn.net/qq_37929553/article/details/118359606