Spring5 (the third day)

AOP (concept)

1. What is AOP
(1) Aspect-oriented programming (aspect), using AOP can isolate each part of business logic, thereby
reducing the coupling between various parts of business logic, improving the reusability of the program, and at the same time improving Development efficiency.
(2) Popular description: Add new functions to the main function without modifying the source code
(3) Use login examples to illustrate AOP
Insert picture description here

AOP (underlying principle)

Agency model

Why learn the agency model? Because this is the classification of SpringAOP [SpringAOP and SpringMVC]
proxy mode:

  • Static proxy
  • Dynamic proxy
    Insert picture description here
Static proxy

Role analysis:

  • Abstract role: generally use interfaces or abstract classes to solve
  • Real role: the role being proxied
  • Acting role: After acting for the real role, we usually do some subsidiary operations
  • Client: the person who visits the proxy object
    Code steps:
    1. Interface
//租房
public interface Rent {
    
    
    public void rent();

2. Real characters

//房东
public class Host implements Rent{
    
    
    @Override
    public void rent() {
    
    
        System.out.println("房东要出租房子!");
    }
}

3. Acting role

//中介
public class Proxy {
    
    
    private Host host;
    public Proxy(){
    
    }
    public Proxy(Host host){
    
    
        this.host=host;
    }
    public void rent(){
    
    
        host.rent();
    }
    //手续费
    public void getMoney(){
    
    
        System.out.println("获取一些小费");
    }
}

4. Client

//来租房的人
public class Client {
    
    
    public static void main(String[] args) {
    
    
        Host host = new Host();
        Proxy proxy=new Proxy(host);
        proxy.rent();
    }
}

Benefits of the agent model:

  • Can make the operation of real characters more pure! No need to pay attention to some public business
  • Public business is also handed over to the agent role! Realize the division of work!
  • Convenient centralized management when public business expands!
    Disadvantages:
  • A real role will produce an agent role; the amount of code will double-development efficiency will become lower!
Deepen understanding

1. The bottom layer of AOP uses dynamic proxy
(1) There are two kinds of dynamic proxy
. The first is with interface, use JDK dynamic proxy to
create interface to realize class proxy object, and the method to enhance class.
Insert picture description here
The second is without interface, use CGLIB dynamic proxy to
create Proxy objects of subclasses, methods of enhanced classes
Insert picture description here

AOP (JDK dynamic proxy)

1. Use JDK dynamic proxy and use the methods in the Proxy class to create proxy objects

Insert picture description here

(1) Call the newProxyInstance method

Insert picture description here

The method has three parameters: the
first parameter, the class loader, the
second parameter, the class where the enhancement method is located, the interface that this class implements, and supports multiple interfaces. The
third parameter, implements this interface InvocationHandler, creates a proxy object, and writes the enhanced part
2. 、Write JDK dynamic proxy code
(1) Create interface and define method

public interface UserDao {
    
    
public int add(int a,int b);
public String update(String id);
}

(2) Create an interface implementation class and implement methods

public class UserDaoImpl implements UserDao {
    
    
@Override
public int add(int a, int b) {
    
    
return a+b;
}
@Override
public String update(String id) {
    
    
return id;
}
}

(3) Use the Proxy class to create an interface proxy object

public class JDKProxy {
    
    
public static void main(String[] args) {
    
    
//创建接口实现类代理对象
Class[] interfaces = {
    
    UserDao.class};
// Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces,
new InvocationHandler() {
    
    
// @Override
// public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
    
    
// return null;
// }
// });
UserDaoImpl userDao = new UserDaoImpl();
UserDao dao =
(UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces,
new UserDaoProxy(userDao));
int result = dao.add(1, 2);
System.out.println("result:"+result);
}
}
//创建代理对象代码
class UserDaoProxy implements InvocationHandler {
    
    
//1 把创建的是谁的代理对象,把谁传递过来
//有参数构造传递
private Object obj;
public UserDaoProxy(Object obj) {
    
    
this.obj = obj;
}
//增强的逻辑
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws
Throwable {
    
    
//方法之前
System.out.println("方法之前执行...."+method.getName()+" :传递的参
数..."+ Arrays.toString(args));
//被增强的方法执行
Object res = method.invoke(obj, args);
//方法之后
System.out.println("方法之后执行...."+obj);
return res;
}
}

AOP (term)

1. Connection point : the method that can be enhanced in the class.
2. Entry point : the method that is actually enhanced.
3. Notification (enhancement):
(1). The logical part of the actual enhancement is called notification
(2). Multiple types:
front notification
, rear notification,
surround notification,
exception notification,
final notification
4. Aspect: the process of applying notification to the point of entry

AOP operation (preparatory work)

1. The Spring framework is generally based on AspectJ to implement AOP operations
(1) AspectJ is not a part of Spring, it is an independent AOP framework. Generally, AspectJ and Spirng frameworks are
used together to perform AOP operations.
2. AOP operations based on AspectJ
(1) Based on xml Configuration file implementation
(2) Implementation based on annotation method (use)
3. Introduce AOP related dependencies in project engineering
Insert picture description here
4. Pointcut expression
(1) Pointcut expression function: Know which method in which class to enhance
(2) ) Syntax structure: execution([Permission modifier] [Return type] [Class full path] [Method name].([Parameter list]))
Example 1: Enhance
execution of add in the com.atguigu.dao.BookDao class (* com.atguigu.dao.BookDao.add(...))
Example 2: Enhancing all the methods in the com.atguigu.dao.BookDao class
execution(* com.atguigu.dao.BookDao.* (...))
Example 3: Enhance
execution (* com.atguigu.dao .. (…)) for all classes and methods in the com.atguigu.dao package

AOP operation (AspectJ annotation)

1. Create a class and define methods in the class

public class User {
    
    
public void add() {
    
    
System.out.println("add.......");
}
}

2. Create an enhanced class (write enhanced logic)
(1) In the enhanced class, create methods so that different methods represent different notification types

//增强的类
public class UserProxy {
    
    
public void before() {
    
    //前置通知
System.out.println("before......");
}
}
 

3. Configure notifications
(1) In the spring configuration file, turn on annotation scanning

<?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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-
package="com.atguigu.spring5.aopanno"></context:component-scan>

(2) Use annotations to create User and UserProxy objects
(3) Add annotations @Aspect to the enhanced class

//增强的类
@Component
@Aspect //生成代理对象
public class UserProxy {
    
    
}

(4) Turn on the generation of proxy objects in the spring configuration file

<!-- 开启 Aspect 生成代理对象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

4. Configure different types of notifications
(1) In the enhanced class, add notification type annotations as notification methods, and use the entry point expression configuration

//增强的类
@Component
@Aspect //生成代理对象
public class UserProxy {
    
    
//前置通知
//@Before 注解表示作为前置通知
@Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void before() {
    
    
System.out.println("before.........");
}
//后置通知(返回通知)
@AfterReturning(value = "execution(*
com.atguigu.spring5.aopanno.User.add(..))")
public void afterReturning() {
    
    
System.out.println("afterReturning.........");
}
//最终通知
@After(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void after() {
    
    
System.out.println("after.........");
}
//异常通知
@AfterThrowing(value = "execution(*
com.atguigu.spring5.aopanno.User.add(..))")
public void afterThrowing() {
    
    
System.out.println("afterThrowing.........");
}
//环绕通知
@Around(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws
Throwable {
    
    
System.out.println("环绕之前.........");
//被增强的方法执行
proceedingJoinPoint.proceed();
System.out.println("环绕之后.........");
}
}

5. Extract from the same entry point

//相同切入点抽取
 //通过@Pointcut(value = "execution(* aop演示.aop基于注解方式.User.add(..))")
 //后续的所有使用到之前那个切入表达式的地方,替换成basePointCut()这个方法名,以此指向同一个的切入点表达式。
@Pointcut(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
public void pointdemo() {
    
    
}
//前置通知
//@Before 注解表示作为前置通知
@Before(value = "pointdemo()")
public void before() {
    
    
System.out.pr

6. There are multiple enhancement classes with the same method to enhance, set the enhancement class priority
(1) Add the annotation @Order (number type value) to the enhancement class, the smaller the number type value, the higher the priority

@Component
@Aspect
@Order(1)
public class PersonProxy

7. Fully use annotation development
(1) Create configuration class, no need to create xml configuration file

@Configuration
@ComponentScan(basePackages = {
    
    "com.atguigu"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
    
    
}

Go to spring5 (day 4)

Guess you like

Origin blog.csdn.net/qq_44788518/article/details/108101061