Summary of important knowledge points of Spring framework (3)

1. What is AOP?

1. AOP (Aspect Oriented Programming), which uses the isolation of various parts of the business logic, thereby reducing the coupling between the various parts of the business logic, improving the reusability of the program, and improving the efficiency of development.
2. AOP adopts a horizontal extraction mechanism to replace the repetitive code of the traditional vertical inheritance system (performance monitoring, transaction management, security inspection, caching)

2. Why should I learn AOP?

Because it is possible to enhance the existing methods during operation without modifying the source code.

3. What are the advantages of AOP?

  1. Reduce repetitive code 2. Provide development efficiency 3. Convenient maintenance

Four, the underlying principle of AOP

Dynamic proxy technology of JDK (mainly)

1. Create a bytecode file of the proxy class for the interface
2. Use ClassLoader to load the bytecode file into the JVM
3. Create an instance object of the proxy class and execute the target method of the object

cglib proxy technology

Five, AOP related terms

Joinpoint (connection point) The so-called connection point refers to those points that are intercepted. It refers to all methods in spring, because spring only supports connection points of method types.

Pointcut (pointcut) -(write pointcut expression), program enhancement entry.

Advice (information/enhancement)-to enhance the method in spring, write transaction management related code.

Target-the target of the agent

Weaving -refers to the process of applying enhancements to the target object to create a new proxy object

Proxy -After a class is woven and enhanced by AOP, a resulting proxy class is generated

Aspect = entry point + notification

Six, entry case

(1) First, briefly talk about the next steps

①Introduce new coordinate AOP, Spring-aspects, aspect; ②Introduce specific AOP constraints in configuration file; ③Write package structure, write specific interface and implementation class; ④Inject target class; ⑤Define aspect class; ⑥In configuration file injecting aspect class; complete AOP configuration; test

(2) Specific implementation

① Introduce new coordinate AOP, Spring-aspects, aspect;

    <dependency>
        <groupId>aopalliance</groupId>
        <artifactId>aopalliance</artifactId>
        <version>1.0</version>
    </dependency>
    <!-- Spring Aspects -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <!-- aspectj -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.3</version>
    </dependency>

②The configuration file introduces specific AOP constraints;

<?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">

③Write the package structure, write specific interfaces and implementation classes;

接口:
package demo3;
public interface UserService {
    public void save();
}
实现类:
package demo3;
public class UserServiceImpl implements UserService {
    public void save() {
        System.out.println("业务层:保护用户...");
    }
}

④Inject the target class;

<bean id="userService2" class="demo3.UserServiceImpl">

⑤ Define the aspect category;

package demo3;
/*
* 自定义切面类 = 切入点(表达式) + 通知(增强的代码)
* */
public class MyXmlAspect {
    /*通知*/
    public void log(){
        System.out.println("增强的方法执行了......");
    }
}

⑥Inject facets into the configuration file;

<bean id="myXmlAspect" class="demo3.MyXmlAspect"/>

⑦Complete AOP configuration;

<!--
             切入点的表达式:
                   execution() 固定的写法
                   public          是可以省略不写的
                   方法的返回值      int String 通用的写法,可以编写 * 不能省略不写的
                   包名+类名        不能省略不写的,编写 *  UserServiceImpl AccountServiceImpl
                   方法名称         save() 可以写 *
                   参数列表         (..) 表示任意类型和个数的参数
                   比较通用的表达式:execution(public * cn.tx.*.*ServiceImpl.*(..))
            -->

<aop:config>
            <!--配置切面 = 切入点 + 通知组成-->
            <aop:aspect ref="myXmlAspect">
                <!--前置通知-->
                <aop:before method="log" pointcut="execution(public * demo3.UserServiceImpl.save(..)))"/>
            </aop:aspect>
</aop:config>

⑧Write test class for testing

//运行单元测试  切记需要单元测试环境  导入spring-test
@RunWith(SpringJUnit4ClassRunner.class)
//加载类路径下的配置文件
@ContextConfiguration("classpath:applicationContext4.xml")
public class demo4 {
    //按照类型自动导入
    @Autowired
    private UserService userService;

    /*测试*/
    @Test
    public void run(){
        userService.save();
    }
}

(3) AOP notification types

<!--
                AOP的通知类型
                    前置通知:目标方法执行前,进行增强。
                        <aop:before method="log" pointcut="execution(* cn.tx.*.*ServiceImpl.save*(..))" />
                    最终通知:目标方法执行成功或者失败,进行增强。
                        <aop:after method="log" pointcut="execution(* cn.tx.*.*ServiceImpl.save*(..))" />
                    后置通知:目标方法执行成功后,进行增强。
                        <aop:after-returning method="log" pointcut="execution(* cn.tx.*.*ServiceImpl.save*(..))" />
                    异常通知:目标方法执行失败后,进行增强。
                        <aop:after-throwing method="log" pointcut="execution(* cn.tx.*.*ServiceImpl.save*(..))" />
                    环绕通知:目标方法执行前后,都可以进行增强。目标对象的方法需要手动执行。
            -->

Seven, Spring's AOP technology-annotation method

Based on the above
1, add annotation @Aspect to the aspect class, write enhanced methods, and use notification type annotation declarations

@Component  // 把该类交给IOC去管理
@Aspect     // 声明是切面类  == <aop:aspect ref="myXmlAspect">
public class MyXmlAspect {

    /*通知*/
    // @Before(value = "切入点的表达式")
    @Before(value = "execution(public * demo3.UserServiceImpl.save(..))")
    public void log(){

        System.out.println("增强的方法执行了......");
    }
}

2. Turn on automatic proxy in the configuration file

<!--开启注解扫描-->
        <context:component-scan base-package="demo3"/>

        <!--开启自动代理--> c
        <aop:aspectj-autoproxy/

Eight, Spring's AOP technology-pure annotation method

Notification type annotation
@Before – pre-notification
@AfterReturing – post-notification
@Around – surrounding notification (the target object method is not executed by default and needs to be executed manually)
@After – final notification
@AfterThrowing – notification of exception throwing

Write configuration class

@Configuration      // 配置类
@ComponentScan(value = "cn.tx.demo3")   // 扫描包
@EnableAspectJAutoProxy     // 开启自动代理 == <aop:aspectj-autoproxy />
public class SpringConfig {
    
}

Summary of important knowledge points of Spring framework (4) .

Guess you like

Origin blog.csdn.net/javaScript1997/article/details/108060839