I heard that wechat search “Java fish” will change strong oh!

This article is in Java Server, which contains my complete series of Java articles, can be read for study or interview

(1) Overview

Now that we’ve covered one of Spring’s core IOC, let’s move on to the other core of Spring –Spring AOP. AOP translates as aspect oriented programming, and those who have just come into contact with it certainly do not understand what aspect oriented programming is. In simple terms, aspect is the isolation of various parts of business logic.

The most common is the separation of logs from business logic, so we can use AOP to write logs before and after the execution of business logic without touching the already written business logic code.

(2) Some concepts of AOP

There are several concepts in AOP:

  • Which classes and methods do pointcuts cut into?

  • Advice what to actually do (when: before method/after method/before and after method) when a method executes (what: enhanced functionality)

  • Aspect

Aspect = pointcut + notification, popular point is: when, where, what to do enhancement!

  • Weaving

The process of adding facets to an object and creating a proxy object. (This is done by Spring) by setting pointcuts, advice, and aspects to implement what AOP wants to do.

AOP defines five types of notification: pre-notification, post-notification, return notification, exception notification, and surround notification.

Represents the point in time at which the advice is executed, such as before the business code is executed.

The above concept is known, and the next will be through the code to deepen the impression.

(3) Use Spring to implement AOP

When using AOP, you need to import a dependency package, which is also required for Spring

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.9. RELEASE</version>
</dependency>
Copy the code

To simulate a business scenario, we write an interface and implementation class that simulate business logic:

public interface Service {
    public void add(a);
    public void select(a);
    public void update(a);
    public void delete(a);
}
Copy the code

An implementation class that emulates business logic

public class ServiceImpl implements Service {
    public void add(a) {
        System.out.println("add");
    }
    public void select(a) {
        System.out.println("select");
    }
    public void update(a) {
        System.out.println("update");
    }
    public void delete(a) {
        System.out.println("delete"); }}Copy the code

I also registered my beans with the Spring container in bean.xml, where I introduced the dependencies REQUIRED by AOP.


      
<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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    <! Registered bean -- -- -- >
    <bean id="service" class="com.javayz.service.ServiceImpl"/>
</beans>
Copy the code

3.1 AOP is implemented through Spring’s API

There are two ways to implement AOP. The first way is through Spring’s API. We create a new package called log and create a BeforeLog in it:

public class BeforeLog implements MethodBeforeAdvice {
    / * * *@paramMethod Specifies the method of the target object to execute@param* objects parameters@paramO Target object *@throws Throwable
     */
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println(o.getClass().getName()+"Of this class"+method.getName()+"This method is executed."); }}Copy the code

This class inherits MethodBeforeAdvice, which means this is a pre-notification and needs to implement the before method with three arguments:

Method Specifies the Method of the target object to execute

The Object parameters

Object Target Object

Does that look familiar to you? Yeah, it’s like a dynamic proxy. We’re going to print a piece of data here.

You then register the beans in the Spring container in bean.xml and configure AOP

<! Registered bean -- -- -- >
<bean id="service" class="com.javayz.service.ServiceImpl"/>
<bean id="beforeLog" class="com.javayz.log.BeforeLog"/>

<! - the configuration of aop -- -- >
<aop:config>
    <! Execution of the execution expression -->
    <aop:pointcut id="pointcut" expression="execution(* com.javayz.service.ServiceImpl.*(..) )"/>
    <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
</aop:config>
Copy the code

Aop is configured in two steps. The first step is to configure a pointcut, which is the place to execute, using an execution expression:

execution(* com.javayz.service.ServiceImpl.*(..) )

The first asterisk indicates the return type, and * indicates all types

This is followed by a method of a class under the package name to be intercepted, with * for all methods, the final parentheses for method arguments, and two dots for any arguments.

The second step is to configure notification, where before notification is configured.

Write a test method:

@Test
public void test2(a){
    ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
    Service service = (Service) context.getBean("service");
    service.add();
}
Copy the code

Observation results after execution:

By executing our cut-in method in front of the business logic code, AOP implements the cut-in of the other module code without touching the business code.

3.2 Implement AOP with custom facets

The above method is intuitive, but too complex, we can define our own slice

public class MyAspect {
    public void before(a){
        System.out.println("Business before business");
    }
    public void after(a){
        System.out.println("Business after execution"); }}Copy the code

Next, configure bean.xml

<bean id="myAspect" class="com.javayz.aspect.MyAspect"/>
<aop:config>
    <aop:aspect ref="myAspect">
        <aop:pointcut id="pointcut" expression="execution(* com.javayz.service.ServiceImpl.*(..) )"/>
        <aop:before method="before" pointcut-ref="pointcut"/>
    </aop:aspect>
</aop:config>
Copy the code

First register your own defined aspect, then introduce AOP and set up pointcuts. Aop will give you five ways to cut in if you use IDEA, select before.

Execute the above test code again and observe the result:

(4) Use annotations to implement AOP

AOP is easier to implement using annotations, which first define a facet class:

// mark this class as an aspect
@Aspect
public class AnnotationAspect {

    @Before("execution(* com.javayz.service.ServiceImpl.*(..) )"
    public void before(a){
        System.out.println("Method before execution"); }}Copy the code

It is indicated that this is a section by @Aspect, and there are five annotations by @before, @after, @around, @afterreturning and @afterthrowing.

Then configure the open annotation in the configuration file:

<! - injection bean -- -- >
<bean id="annotationAspect" class="com.javayz.annotation.AnnotationAspect"/>
<! -- Enable annotation support -->
<aop:aspectj-autoproxy/>
Copy the code