Spring 5 core technology AOP basic project practice detailed record

table of Contents

One, understand the Spring framework

2. Inversion of control and dependency injection (IoC+DI)

3. Aspect-Oriented Programming (AOP)

1. AOP principle

2. Six basic concepts of AOP

Horizontal focus

section

Junction

Cut-off point

Notice

Four, AOP use core cases

1. Create a new Spring project

2. Create a simple business class

3. Create an aspect class 

4. Create a configuration class

5. Create the main test class

Five, BUG solutions

1、Bug1:java.util.prefs.WindowsPreferences

2、Bug2:WARN Please initialize the log4j system properly


One, understand the Spring framework

I have always admired the name Spring for a long time, but I don’t know what it is. I have recently started learning from scratch and have some basic understanding, so I record it here.

In fact, I am very curious about the origin of the name of the Spring framework and checked it out specifically:

The name comes from the natural world. In fact, Spring represents the traditional J2EE winter past, marking a new era of Java EE development, so I agree with this simple and elegant name.

The power of the Spring framework is that it simplifies the J2EE development and encapsulates most of the commonly used functions. The realization principle relies on two technical principles: Inverse of Control and Aspect Oriented Programming.

The Spring framework consists of major modules. In Spring 5, there are:

  1. Core module Core: dependency injection (DI), aspect-oriented programming (AOP), event processing (events), resource access (resources), data binding (data binding), i18n (internationalization), etc.
  2. Testing module Testing: Support Spring MVC Test, WebTestClient, TestContext Framework, mock objects testing framework.
  3. Data access module Data Access: transaction processing (transaction), data access object (DAO), database connection (JDBC), object-relational mapping (ORM) and processing XML (Marshalling XML).
  4. Spring MVC module and Spring WebFlux Web Framework module
  5. Integration module Integration: remote access (remoting), message service (JMS), encryption and decryption (JCA), management extension (JMX), mail management (mail), etc.
  6. Languages Supported : Support development in languages ​​such as Kotlin and Groovy.

After learning this, I found that Spring's functions are particularly comprehensive and powerful. "There is a way to learn from a mountain, and there is no end to learning." Once again, it gives the best interpretation. For Xiaobai who is just learning, I don't know where to start. The most basic part is also a very important technical principle to start learning.

2. Inversion of control and dependency injection (IoC+DI)

In ordinary programming projects, if you want to use the B.java class in A.java, you must instantiate the B class object in A, resulting in a tight coupling between A and B, which becomes "intrusive development" ". Assuming that as the project is updated and upgraded, more functions need to be added, and a large number of extensions and changes are required for category B in the business code, so that category A also needs to be changed. Obviously, this is not conducive to software update and maintenance.

Therefore, Spring's IoC technology solves this problem and realizes the inversion of control through reflection technology. IoC separates the caller A from the callee B, and decouples the direct relationship between the class and the class to meet the expectations of "low coupling".

As shown in the figure above, the IoC technology of the Spring framework realizes the decoupling of class A and class B. In class A, there is no need for new B(). Instead, the instantiation task is handed over to Spring to complete, and then the reflection mechanism is used to instantiate the object. Assigned to the b object in A.

Originally, A took the initiative to instantiate an object of type B, but now it has become a passive party. It is realized by the Spring framework, which realizes the inversion, so it is called "inversion of control".


IoC has become a design idea here, and the specific implementation method of assignment is dependency injection (DI) . The container that manages JavaBeans in Spring is the IoC container. The above B-type object is created by the container, and the container injects the object value of b in A. Therefore, DI uses reflection technology to dynamically assign class attributes. IoC/DI separates interfaces and implementation methods from the perspective of programming technology. The IoC container manages the life cycle of JavaBeans and the injection relationship of multiple JavaBeans.

3. Aspect-Oriented Programming (AOP)

The birth of a technology must be to solve a type of problem, Spring's AOP technology is to solve the universal problems in software projects, such as program log information, including information such as execution time, executor, efficiency, and results.

If the log code is added or deleted in the source program, it will affect the efficiency of the program operation, and it is difficult to maintain the software modularly, which is cumbersome. Therefore, the dynamic proxy-based AOP technology can extend the functions of the original module without modifying the code, decouple the common log module, and facilitate modular management.

For example, adding logging function without changing the Servlet code; adding database transaction function without changing the control layer code of the Spring MVC framework.

1. AOP principle

Spring AOP technology is based on the principle of the proxy design pattern, the so-called proxy, the understanding here is to provide a proxy for other objects to control access to this object. Sometimes, an object is not suitable or cannot directly refer to another object, and the proxy object needs to act as an intermediary between the client and the target object.

The proxy design mode is divided into static proxy and dynamic proxy. Static proxy is not conducive to expansion because the proxy class is bound to a fixed interface. We mainly learn about dynamic proxy.

In Java, there are 4 common ways to implement dynamic agents:

  1. Dynamic proxy provided by JDK
  2. cglib framework
  3. javaassist framework
  4. Spring framework

The following case will use the Spring framework to implement AOP dynamic proxy.

2. Six basic concepts of AOP

  • Horizontal focus

The horizontal focus is the function of versatility. Commonly used horizontal concerns include method execution time recording, access authorization verification, regular logs, and database transaction processing .

It separates common codes such as log function code and Service business code to achieve the purpose of decoupling. Different from the nature of DI, the decoupling of AOP is mainly the separation between the code of the horizontal focus and the business code, while the dependency injection is the decoupling between objects.

  • section

Aspects are the modularization of horizontal focus points. Each aspect is the realization of a horizontal focus point function. It extracts common codes and puts them into separate classes for unified processing, which is convenient for reuse. This class is the aspect class, and aspect-oriented programming is to write code mainly on the aspect.

  • Junction

The connection point is a point in the software program that can be inserted into the cut surface. The location of the connection point can be before/after the method is called, when an exception is thrown, after the return value, etc.

  • Cut-off point

The cut point is a part of the connection point, a concept that reduces the number of connection points, applies the cut surface to the cut point, and improves the efficiency of software operation.

  • Notice

In Spring AOP, there are five types of notifications:

(1) Before notice (Before): Before the method is called.

(2) After notification (After): After the method is called.

(3) Around notification (Around): Before and after the method is called.

(4) After-returning: The method has a return value.

(5) After-throwing: The method is abnormal.

The aspect contains the notice and the point of contact, which is a combination of the two. It is easier to understand that the notification defines the timing of applying the aspect; the tangent point defines where the aspect is placed.

Four, AOP use core cases

A lot of the previous knowledge may not be understood, "it’s always shallow on paper." Then, in the simple application of AOP, it will be more intuitive to see the application of the theory in practice.

IDE: Intellij IDEA U version

JDK:jdk1.8.0

Spring:Spring 5.2.3

Aspect:Aspectj1.9

1. Create a new Spring project

Create the package Spring_AOP under the src file. My file structure is as follows:

Use annotations to implement the aforementioned advice. Annotations are an important application in Spring, which can reduce the tedious work of manually configuring xml.

2. Create a simple business class



/*
 * UserinfoService.java
 * Copyright (c) 2021-02-25
 * LastModified:2021/2/25 上午10:48
 * Author : Charzous
 * Blog : https://blog.csdn.net/Charzous
 * All right reserved.
 */

package Spring_AOP.aopDemo.service;

import org.springframework.stereotype.Service;

@Service(value = "a")
public class UserinfoService {
    public void method1() {
        System.out.println("method 1 ");
    }

    public String method2() {
        System.out.println("method 2");
        return "我是方法2返回值";
    }

    public String method3() {
        System.out.println("method 3:测试异常");
        Integer.parseInt("a");//测试error
        return "我是方法3返回值";
    }
}

3. Create an aspect class 



/*
 * AspectObject.java
 * Copyright (c) 2021-02-25
 * LastModified:2021/2/25 上午10:55
 * Author : Charzous
 * Blog : https://blog.csdn.net/Charzous
 * All right reserved.
 */

package Spring_AOP.aopDemo.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AspectObject {


    @Around(value = "execution(* Spring_AOP.aopDemo.service.UserinfoService.*(..))")//
    //注解实现环绕通知
    public Object around(ProceedingJoinPoint point) {
        Object returnObject = null;
        try {
            System.out.println("环绕开始");
            returnObject = point.proceed();
            System.out.println("环绕结束");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return returnObject;
    }

    //*:任意返回值;service.UserinfoService.* service包下UserinfoService类中任意方法;.. 任意类型的参数
    @Before(value = "execution(* Spring_AOP.aopDemo.service.UserinfoService.*(..))")
    public void before() {
        System.out.println("Before 方法");
    }

    @After(value = "execution(* Spring_AOP.aopDemo.service.UserinfoService.*(..))")
    public void after() {
        System.out.println("After 方法");
    }

    @AfterReturning(value = "execution(* Spring_AOP.aopDemo.service.UserinfoService.*(..))")
    public void afterReturning() {
        System.out.println("afterReturning");
    }

    @AfterThrowing(value = "execution(* Spring_AOP.aopDemo.service.UserinfoService.*(..))")
    public void afterThrowing() {
        System.out.println("afterThrowing");
    }

}

 The pre-, post-, return, surround and exception notification are implemented in the code, and aspect expressions are used to match business classes.

It can be seen that the aspect expressions are consistent, and further optimization can reduce the expression redundancy through the global tangent point .



/*
 * AspectObject.java
 * Copyright (c) 2021-02-25
 * LastModified:2021/2/25 上午10:55
 * Author : Charzous
 * Blog : https://blog.csdn.net/Charzous
 * All right reserved.
 */

package Spring_AOP.aopDemo.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AspectObject {
    //使用全局切点,使表达时全局化,减少冗余
    @Pointcut(value = "execution(* Spring_AOP.aopDemo.service.UserinfoService.*(..))")
    public void publicPointCut(){

    }

    @Around(value = "publicPointCut()")//"execution(* Spring_AOP.aopDemo.service.UserinfoService.*(..))"
    //注解实现环绕通知
    public Object around(ProceedingJoinPoint point) {
        Object returnObject = null;
        try {
            System.out.println("环绕开始");
            returnObject = point.proceed();
            System.out.println("环绕结束");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return returnObject;
    }

    //*:任意返回值;service.UserinfoService.* service包下UserinfoService类中任意方法;.. 任意类型的参数
    @Before(value = "publicPointCut()")
    public void before() {
        System.out.println("Before 方法");
    }

    @After(value = "publicPointCut()")
    public void after() {
        System.out.println("After 方法");
    }

    @AfterReturning(value = "publicPointCut()")
    public void afterReturning() {
        System.out.println("afterReturning");
    }

    @AfterThrowing(value = "publicPointCut()")
    public void afterThrowing() {
        System.out.println("afterThrowing");
    }

}

4. Create a configuration class

Use annotations to scan each class in the specified package, and Spring will complete the automatic configuration. This class also implements Spring dynamic proxy. Note that you need to use the full package name to configure it correctly.



/*
 * MyContext.java
 * Copyright (c) 2021-02-25
 * LastModified:2021/2/20 下午10:28
 * Author : Charzous
 * Blog : https://blog.csdn.net/Charzous
 * All right reserved.
 */

package Spring_AOP.aopDemo;


import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = {"Spring_AOP.aopDemo.service","Spring_AOP.aopDemo.aspect"})
public class MyContext {
}

5. Create the main test class



/*
 * aopDemo_test.java
 * Copyright (c) 2021-02-25
 * LastModified:2021/2/20 下午6:58
 * Author : Charzous
 * Blog : https://blog.csdn.net/Charzous
 * All right reserved.
 */

package Spring_AOP.aopDemo;

import Spring_AOP.aopDemo.service.UserinfoService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class aopDemo_test {
    public static void main(String[] args) {
        ApplicationContext context=new AnnotationConfigApplicationContext(MyContext.class);
        UserinfoService service=(UserinfoService) context.getBean(UserinfoService.class);
        service.method1();
        System.out.println();
        System.out.println("get method 2 return value="+service.method2());

        System.out.println();
        System.out.println("get method 3 return value="+service.method3());
    }
}

 As you can see, ApplicationContext uses annotations to parse the context, and the other way is XML file parsing.

Method 3 test exception notification, the results are as follows:

Five, BUG solutions

1、Bug1:java.util.prefs.WindowsPreferences <init>

When I was testing and running the program, a warning appeared.

java.util.prefs.WindowsPreferences <init>

WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.

Although it does not affect the operation, it is better to solve it.

solve:

Open the Windows Registry Editor and find the following directory

HKEY_LOCAL_MACHINE\Software\JavaSoft

Then create a new folder Prefs.

2、Bug2:WARN Please initialize the log4j system properly

Another warning appears:

log4j:WARN No appenders could be found for logger (org.springframework.XXX).
log4j:WARN Please initialize the log4j system properly.

This is the log4j message log framework in Mybatis, because another package I created uses the Mybatis framework, which has little effect on this run and outputs warning messages.

solve:

Only need to create a new log4j.properties file under src , the content is:

#
# log4j.properties
# Copyright (c) 2021-02-25
# LastModified:2021/2/24 下午9:42
# Author : Charzous
# Blog : https://blog.csdn.net/Charzous
# All right reserved.
#

log4j.rootLogger=WARN, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

 At this point, the simple basic practices of Spring 5 core technology AOP have been completed. The power of the Spring framework is that it simplifies the J2EE development and encapsulates most of the commonly used functions. The realization principle relies on two technical principles: Inversion of Control (IoC) and Aspect-Oriented Programming (AOP). This article mainly understands the basic knowledge of Spring and the realization of AOP, and has some basic understanding, so it is recorded here.

If you think it’s good, welcome to "one-click, three-link", like, bookmark, follow, comment directly if you have any questions, and exchange and learn! 


My CSDN blog: https://blog.csdn.net/Charzous/article/details/114044697

Guess you like

Origin blog.csdn.net/Charzous/article/details/114044697