Spring - study notes

1. Introduction to Spring

Concept: Spring is an open source enterprise-level application development framework, which provides comprehensive infrastructure support and rich functional modules for Java applications. The goal of Spring is to simplify Java development, improve development efficiency, code quality and maintainability.

  • Aim: It exists to solve the complexity of enterprise-level application development;
  • Core: The core of Spring is to provide a container.
    This container will create and manage the components of the application. The components are called beans, and the beans will be assembled together through this container to form a complete application.
    The container is called the Spring application context;
    the behavior of assembling beans together is realized through the pattern of dependency injection DI;
  • effect:
    • Let Java Bean之间be more efficient 解耦; (DI/Ioc)
    • Spring support 面向切面编程; (AOP)
    • 整合其他框架和技术; (Hibernate、MyBatis、Spring MVC、Spring Data、Spring Security)
    • 声明式事务管理mechanisms provided ;
    • strong 测试support;

Spring-related development patterns

  • SSH(Spring-Struts-Hibernate)
    1. Spring Framework: As a lightweight container, Spring is responsible for managing objects, dependency injection, transaction management, etc. in the application. It provides many functions, such as IoC (Inversion of Control), AOP (Aspect-Oriented Programming), etc., to simplify the development process and increase the maintainability of the code.

    2. Struts framework: Struts is a Web framework based on the MVC (Model-View-Controller) design pattern. It is responsible for processing HTTP requests, mapping requests to corresponding processors (Actions) for processing, and presenting processing results to users. The Struts framework provides a set of extensible Action processing mechanisms for processing user requests and managing page jumps.

    3. Hibernate Framework: Hibernate is an object-relational mapping (ORM) framework for mapping data in a database into Java objects. It is responsible for handling the details of data persistence, including database connection, SQL generation, transaction management, etc. Hibernate provides a simple API and query language, making it easier for developers to operate the database.

//

  • SSM(Spring-SpringMVC-MyBatis)
    1. Spring Framework: As a lightweight container, Spring is responsible for managing objects, dependency injection, transaction management, etc. in the application. It provides many functions, such as IoC (Inversion of Control), AOP (Aspect-Oriented Programming), etc., to simplify the development process and increase the maintainability of the code.

    2. SpringMVC framework: SpringMVC is a web framework based on the MVC (Model-View-Controller) design pattern. It is responsible for processing HTTP requests, mapping requests to corresponding processors (Controllers) for processing, and presenting processing results to users. The SpringMVC framework provides a set of flexible processor mapping mechanism, data binding and view resolution functions for building front-end controllers of web applications.

    3. MyBatis framework: MyBatis is a persistence layer framework for mapping database operations to Java objects. It provides a simple way to write data access objects (DAO) through XML or annotation configuration. The MyBatis framework is responsible for database connection, SQL execution, result mapping, etc., making it easier for developers to operate the database.

1.1 Spring architecture

insert image description here

1. Core Container (core container)

Spring's core container is the foundation upon which other modules are built.

  • Beans module: Provided BeanFactory, it is a classic implementation of the factory pattern, and Spring refers to the management object as a Bean.
  • Core core module: Provides the basic components of the Spring framework, including IoC和DIfunctions.
  • Context module: Built on the basis of Core and Beans modules, it is a medium for accessing any object defined and configured. where ApplicationContext接口is the focus of the context module.
  • Context-support module: provides support 第三方库嵌入Spring应用的集成支持, such as caching (EhCache, Guava, JCache), mail service (JavaMail), task scheduling (CommonJ, Quartz) and template engines (FreeMarker, JasperReports, rate).
  • SpEL module: It is a new module after Spring 3.0. It provides Spring Expression Language support and is a powerful tool for querying and manipulating object graphs at runtime 表达式语言.

2.Data Access/Integration (data access/integration)

  • JDBC module: Provides a JDBC abstraction layer, which greatly reduces the coding of database operations during the development process.
  • 对象关系映射APIORM module: provides integration layer support for popular ones , including JPA, JDO and Hibernate.
  • OXM module: Provides an 支持对象/ XML映射abstraction layer implementation, such as JAXB, Castor, XMLBeans, JiBX and XStream.
  • JMS module: refers to Java消息传递the service, including the characteristics of using and generating information, and supports the integration with the Spring-message module since version 4.1.
  • 特殊接口Transactions transaction module: supports programming and declarative transaction management for implementation and all POJO classes.

3.Web

  • WebSocket module: It provides the implementation of WebSocket and SockJS, as well as support for STOMP.
  • Servlet module: also known as Spring-webmvc module, contains Spring's (MVC) and REST Web Services implemented Web applications.
  • Web module: Provides basic web development integration features, such as: multi-file upload function, use Servlet listener to initialize IoC container and web application context.
  • Portlet module: Provides the use of MVC in the Portlet environment, similar to the function of the Servlet module.

4. other modules

  • AOP module: Provides 面向切面programming implementation, allows the definition of method interceptors and entry points, and separates code according to function to reduce coupling.
  • Aspects module: Provides integration with AspectJ, a powerful and mature aspect-oriented programming (AOP) framework.
  • Instrumentation module: Provides the support of class tools and the implementation of class loaders, which can be used in specific application servers.
  • Messaging module: A new module added after Spring 4.0, which provides 消息传递support for architecture and protocols.
  • Test module: Provides support for unit testing and integration testing.

2. DI/Ioc (Dependency Injection/Inversion of Control)

One of the roles of Spring: to make Java Bean之间more efficient解耦

理解Bean 之间的解耦:
传统的 Java 开发中,对象之间的依赖关系通常是通过直接实例化和引用其他对象来建立的,
这导致了高度的耦合性。

---------------------------------------------------------------------------
举例:
public class UserService {
    private UserDao userDao = new UserDao();

    public void createUser(User user) {
        // 使用 userDao 对象进行用户数据的持久化操作
        userDao.save(user);
    }
}

这里存在两个类:UserService 和 UserDao。
UserService 是一个用户服务类,依赖于 UserDao 来进行用户数据的持久化操作。

-------------------------------------------------------------------------------------------
UserService 类在自己的代码中直接创建了一个 UserDao 对象,并将其作为成员变量进行引用。
这种方式存在的问题:
1. Service 类与具体的 User 类紧密耦合在一起,User类如果发生改变,service也需要修改。
2. service如果被使用,还需要额外管理UserDao对象的生命周期。
3. 进行测试项目时,无法将service单独进行测试。

concept

IOC (Inversion of Control) and DI (Dependency Injection) are closely related concepts, mainly used to 解耦对象之间的依赖关系improve code flexibility, maintainability and testability.
//
IOC (Inversion of Control) is a design 原则, "transfer of control of an object"

  • Refers to the control of the creation of objects and the management of dependencies to the container, rather than the explicit creation and management of objects by the application code (in the traditional programming model, the application code is responsible for creating and managing objects, and in In IOC mode, this control is transferred to the container).

DI (Dependency Injection) is a way of IOC 实现, "Description of dependencies between objects is resolved by injection"

  • Refers to injecting dependencies into objects through containers.
    In dependency injection, objects are no longer responsible for the creation of their own dependencies, but receive dependent objects through constructors, properties, or method parameters.
    Dependency injection can be 通过接口、注解或配置来实现used to achieve decoupling and flexibility between objects.

2.1 Dependency and annotations

1. lombok
<!--        简化实体类的开发,通过注解自动化生成Java类的样板代码,如Getter、Setter、构造函数、equals()和hashCode()等方法-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.28</version>
        </dependency>

Create an entity class and use to @Data注解automatically generate methods such as get set

package com.imooc.pojo;

import lombok.Data;

@Data
public class Student {
    
    

    private long id;
    private String name;
    private int age;
}

The Student object is directly created and assigned in the test class.

package com.imooc.test;

import com.imooc.pojo.Student;

public class UserDemo {
    
    
    public static void main(String[] args) {
    
    

        Student student = new Student();
        student.setId(1);
        student.setName("tudou");
        student.setAge(2);
        System.out.println(student);
    }
}

insert image description here

2. spring-context

The spring-context module is one of the core modules of the Spring framework, providing the functionality of the IoC (Inversion of Control) container and other features related to the application context.

<!--        Spring上下文依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>

2.2 Bean and Spring context configuration

Way:

  1. Based on xml file;
  2. Configuration based on java annotations;
  3. automatic configuration
Method 1: Based on xml文件configuration

1. Create an xml file under resource as a configuration file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

Create entity classes

package com.imooc.pojo;

import lombok.Data;

@Data
public class Student {
    
    

    private long id;
    private String name;
    private int age;
}

Introduce entity class in xml

id: object name
class: template class of the object (all classes handed over to Ioc management must have a no-argument construction method)
member variables are assigned through property tags

  • name: member variable name
  • value: member variable value (basic data type)
  • ref: assign another bean in ioc to the current bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="student" class="com.imooc.pojo.Student">
        <property name="id" value="1"></property>
        <property name="name" value="zhangsan"></property>
        <property name="age" value="56"></property>
        <property name="address" ref="address"></property>
    </bean>

    <bean id="address" class="com.imooc.pojo.Address">
        <property name="city" value="beijing"></property>
        <property name="home" value="qinghau"></property>
    </bean>
</beans>

test

public class UserDemo {
    
    
    public static void main(String[] args) {
    
    

        Student student = new Student();
        student.setId(1);
        student.setName("tudou");
        student.setAge(2);
        System.out.println(student);

        //加载配置文件
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring.xml");
        Student student1 = (Student)classPathXmlApplicationContext.getBean("student");
        System.out.println(student1);

    }
}


insert image description here

Method 2: Configure beans based on java annotations
annotation illustrate
@Configuration Indicates that the current class is a configuration class, which is equivalent to the previous spring.xml file
@Bean Returns a bean object managed by Spring.
package com.imooc.config;

import com.imooc.pojo.Address;
import com.imooc.pojo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class StudentConfig {
    
    

    @Bean
    public Student student(){
    
    
        Student student = new Student();
        student.setId(2);
        student.setName("lisi");
        student.setAge(66);
        student.setAddress(address());
        return student;
    }

    @Bean
    public Address address(){
    
    
        Address address = new Address();
        address.setCity("南京");
        address.setHome("家");
        return address;
    }
}

import com.imooc.config.StudentConfig;
import com.imooc.pojo.Address;
import com.imooc.pojo.Student;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class StudentDemo {
    
    
    public static void main(String[] args) {
    
    
        // 创建基于注解的应用程序上下文
        AnnotationConfigApplicationContext acac = new AnnotationConfigApplicationContext(StudentConfig.class);

        // 获取配置的bean
        Student bean = acac.getBean(Student.class);
//        Address bean1 = acac.getBean(Address.class);

        // 使用bean
        System.out.println(bean);
    }
}

insert image description here

Method 3: Automated configuration

The @Component annotation is usually used with other related annotations (such as @Service, @Repository, @Controller, etc.) to 标记不同层次或类型的组件tell the Spring framework which packages to scan for annotated components. In this way, the Spring container will 自动实例化use 管理these components for application use.

annotation illustrate
@Component Mark a class as Spring 托管的组件, and the Spring container will take 自动扫描并实例化these components and include them in the application context
@Service A tag 服务层组件indicating that the component is used to handle business logic. Usually, service layer components are used to encapsulate business logic and handle tasks such as data acquisition, conversion, calculation, and manipulation.
@Repository A tag 持久层组件indicating that this component is used to encapsulate data access logic. Typically, persistence layer components are used to interact with databases or other data stores, and perform operations such as reading, writing, updating, and deleting data.
@Controller Used in markup 控制层组件to indicate that this component is used to handle requests and responses. Usually, the control layer components receive user requests, call appropriate service layer components to process the requests, and return responses to users.
//创建配置类
import com.imooc.pojo.Student;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component("student4")
@Service
public class StudentService {
    
    

    public Student createStudentt(){
    
    
        Student student = new Student();
        student.setName("画虎");
        return student;
    }
}

xml automation configuration
configures automatic scanning in spring.xml

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

 
<!--注解组件扫描,扫描指定的基本包及其子包下的类,识别使用@Component注解-->
    <context:component-scan base-package="com.imooc"></context:component-scan>

</beans>

test

public class StudentDemo4 {
    
    
    public static void main(String[] args) {
    
    

        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring.xml");
        StudentService studentService= classPathXmlApplicationContext.getBean(StudentService.class);
        Student studentt = studentService.createStudentt();
        System.out.println(studentt);
    }
}

insert image description here

Automatic scanning of java annotations

package com.imooc.config;

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

//@Configuration声明加载配置类,@ComponentScan指定要扫描的包和子包
@Configuration
@ComponentScan(basePackages = "com.imooc")
public class StudentAutoConfig {
    
    

}

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class StudentDemo5 {
    
    
    public static void main(String[] args) {
    
    
        // 创建一个注解配置的应用上下文
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(StudentAutoConfig.class);

        // 从应用上下文中获取 StudentService 的实例
        StudentService bean = annotationConfigApplicationContext.getBean(StudentService.class);

        // 调用 StudentService 的 createStudentt() 方法创建一个学生对象
        Student studentt = bean.createStudentt();

        // 打印学生对象
        System.out.println(studentt);
    }
}

insert image description here

2.3 Bean instantiation method

Method 1: Static factory

Users are required to create a static factory method to create a bean instance. The class attribute in the bean configuration no longer refers to the bean implementation class, but the static factory class.

  • Use the factory-method attribute to specify the static factory method created

insert image description here
insert image description here
insert image description here

Method 2: Instance factory

In the factory class, directly create the Bean instance;
in the configuration file, first create the configuration factory
and then create the instance factory to point to the configuration factory, and then specify the method
insert image description here

<!--    配置工厂-->
    <bean id="studentFactory" class="com.imooc.factory.StudentFactory"/>
<!--    实例工厂-->
    <bean id="student3"  factory-bean="studentFactory" factory-method="createStudents"></bean>

insert image description here

3. AOP (Aspect Oriented Programming)

AOP (Aspect-Oriented Programming) is a programming paradigm for software development. Its purpose is to improve the modularity, maintainability and reusability of code by separating cross-cutting logic from core business logic.
effect:

  • Simplify the code: extract the repeated code in a fixed position in the method, so that the extracted method can focus more on realizing its core business;

Reason:
In traditional business processing codes, operations such as 事务处理, 日志记录etc. are usually performed.

  • Use to OOP(面向对象)achieve code reuse through combination or inheritance, but if you want to implement a certain function (such as logging), 同样的代码仍然会分散到各个方法中.
  • If you want it 关闭某个功能, or modify it, you have to 修改所有的相关方法. This not only increases the workload of the developers, but also increases the error of the code.

/
AOP adopts a horizontal extraction mechanism to extract the repeated code scattered in each method, and then apply the extracted code to the place where it needs to be executed when the program is compiled or run.

insert image description here

3.1 AOP Terminology

Understand the concept of AOP in one article

keywords explain method
Aspect section The class used 封装横切关注点(also known as the class that encapsulates the notification method)//After encapsulation, a cross-cutting concern represents a notification method.
Joinpoint Junction Logical concepts to extract the location of crosscutting concerns
Pointcut entry point 连接点way of positioning
Advice notify 切面连接点code executed in a specific
Weaving Weave into will 切面be applied to 目标对象the process in
Proxy acting will 通知apply to 目标对象, be 动态创建的对象.

3.2 AOP dependency import

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.0.11.RELEASE</version>
        </dependency>

3.3 Proxy

In AOP (Aspect-Oriented Programming), proxy is the key mechanism to implement aspect functions.

  • A proxy object is created around the target object, which wraps the target object and intercepts method calls on the target object. Through proxy, AOP can realize the separation of cross-cutting concerns, and extract cross-cutting concerns that have nothing to do with core business logic (such as log records, transaction management, security checks, etc.) from the target object.

The relationship between the proxy object and the target object
Example: Every employee goes to the boss’s office to talk to the boss. The boss must first confirm whether he is an internal employee. The role of the agent is equivalent to a work card to help the boss quickly identify internal employees.
//Specific: When each employee goes to the boss's office to talk to the boss, he first needs to verify his identity through the work card. The badge (agent object) will intercept the employee's access request and verify the identity of the employee. Only authenticated employees (legal method calls) can proceed to chat with the boss (target object). While verifying the identity, the badge (proxy object) can also perform other additional tasks, such as the log function: recording the employee's visit time, counting the number of visits of the employee, etc.

Two proxy modes of Spring AOP

JDK dynamic proxy:

  • JDK dynamic proxy is 基于接口the proxy mode.
    When targeting an object 实现了至少一个接口, Spring will use the JDK dynamic proxy to create the proxy object. JDK dynamic proxy uses Java's reflection mechanism to dynamically create proxy objects at runtime. The proxy object implements the same interface as the target object, and inserts crosscutting logic before and after the method call. JDK dynamic proxy requires the target object to implement an interface, so it is more suitable for interface-based proxy scenarios.

CGLIB proxy:

  • CGLIB Proxy is 基于类继承the proxy mode for CGLIB.
    When the target object does not implement any interface, or you want to bypass the restrictions of the interface, Spring will use CGLIB proxies to create proxy objects. CGLIB it passes 创建目标对象的子类来实现代理. The proxy object inherits the class of the target object, rewrites the method of the target object, and adds cross-cutting logic before and after the method call. CGLIB proxy does not require the target object to implement an interface, so it is more flexible and applicable to a wider range of proxy scenarios.

//Note: Objects using JDK dynamic proxy classes must implement one or more interfaces.

JDK dynamic proxy (based on interface proxy)

Implementation steps:

  1. Definition 目标接口(which contains the method to be proxied), defines the implementation class of the target interface;
  2. Create one 代理类(implementing the InvocationHandler interface) that is responsible for intercepting method calls and adding additional logic;
  3. Create 代理对象(using the newProxyInstance method in the Proxy class);
  4. Call the method of the target interface through the proxy object;
//1. 定义目标接口
public interface Employee {
    
    
    void talkToBoss();
}
------------------------------------------------------------
//2.定义目标接口的实现类
public class EmployeeImpl implements Employee{
    
    
    public void talkToBoss() {
    
    
        System.out.println("我说员工,和老板说话了");
    }
}

//目标接口的另一个实现类
public class EmployeeImpl2 implements Employee{
    
    
    public void talkToBoss() {
    
    
        System.out.println("找老板发工资");
    }
}

----------------------------------------------------------------

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//2.定义代理类
public class EmployeeProxy implements InvocationHandler {
    
    

    //声明目标接口
    public Employee employee;

    //创建代理方法
    public Object createProxy(Employee employee){
    
    
        this.employee=employee;
        //2.1 类加载器
        ClassLoader classLoader = EmployeeProxy.class.getClassLoader();
        //2.2 被代理对象实现所有接口
        Class[] classes = employee.getClass().getInterfaces();
        //2.3 使用代理类,进行增强,返回的是代理后的对象
        return Proxy.newProxyInstance(classLoader,classes,this);
    }

    //所有的动态代理方法调用,都会交由invoke()方法处理
    //proxy:被代理后的方法
    //method:要被执行的方法信息(反射)
    //args:执行方法需要的参数
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
        //在方法前添加额外逻辑
        System.out.println("确认身份");
        
        //调用目标方法
        Object invoke = method.invoke(employee, args);
        
        //在方法后添加逻辑
        System.out.println("交谈完毕");

        return invoke;
    }
}
---------------------------------------------------------
//3.测试
public class Test {
    
    
    public static void main(String[] args) {
    
    
        //3.1 创建代理对象
        EmployeeProxy employeeProxy = new EmployeeProxy();

        //3.2 创建目标对象 //员工1找老板
        EmployeeImpl employee = new EmployeeImpl();

        //3.3执行方法
        Employee proxy = (Employee) employeeProxy.createProxy(employee);

        proxy.talkToBoss();

        //员工2找老板
        EmployeeImpl2 employee2 = new EmployeeImpl2();
        Employee proxy1 = (Employee) employeeProxy.createProxy(employee2);
        proxy1.talkToBoss();
    }
}

insert image description here

CGLIB proxy (based on class inheritance proxy)

step

  1. Add dependencies;
  2. Create target class (will be proxied)
  3. Write interceptor class
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

// 定义目标类
class Employee {
    
    
    public void talkToBoss() {
    
    
        System.out.println("与老板交谈");
    }
}

// 实现MethodInterceptor接口的代理处理器类
class EmployeeInterceptor implements MethodInterceptor {
    
    
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    
    
        // 在目标方法执行前添加额外逻辑
        System.out.println("确认员工身份");

        // 调用目标方法
        Object result = proxy.invokeSuper(obj, args);

        // 在目标方法执行后添加额外逻辑
        System.out.println("交谈完毕");

        return result;
    }
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        // 创建Enhancer对象
        Enhancer enhancer = new Enhancer();

        // 设置目标类
        enhancer.setSuperclass(Employee.class);

        // 设置代理处理器
        enhancer.setCallback(new EmployeeInterceptor());

        // 创建代理对象
        Employee proxy = (Employee) enhancer.create();

        // 通过代理对象调用目标方法
        proxy.talkToBoss();
    }
}
Relationship Between AOP and Proxy Pattern

Proxy mode

  • It is one 结构设计模式that controls access to the original object by creating a proxy object, aiming to enhance and control access to the original object without changing it.

AOP

  • One 编程范式, designed to achieve code modularization and reuse by separating cross-cutting concerns (logging, transactions, etc.) from core business logic.
  • 代理模式实现AOPa technical means that can be used as

3.4 Spring AOP

AspectJ: Java-based AOP framework;

  • xml-based
  • annotation based

Annotation-based AspectJ

annotation effect
@Aspect: will be a class 标记为切面类.
@Pointcut: 定义切点, specifying at which join points to apply the aspect.
@Before: Defined 前置通知, executed before the target method is executed.
@After: Defined 后置通知to be executed after the execution of the target method (including exceptions).
@AfterReturning: Defined 返回通知, executed after the target method returns normally.
@AfterThrowing: Defined 异常通知, executed when the target method throws an exception.
@Around: Definition 环绕通知, executed before and after the execution of the target method, and can control the execution process of the target method.
@EnableAspectJAutoProxy: Enables AspectJ 自动代理for automatically creating proxy objects and weaving aspects into target objects.

Notification : For each cross-cutting concern, the implementation on the aspect is realized through the notification method.

notification type illustrate
advance notice Executed before the target method
post notification Executed after the target method 最终结束(including normal return and abnormal return)
return notice 成功结束after target method
Exception notification After the target method ends abnormally
surround notification Use the try–catch–finally structure to surround the entire target method, including the four positions above

AOP注意事项

  • Both the aspect class and the target class need to be handed over to the IOC container for management;
  • The aspect class is represented as an aspect through the @Aspect annotation
  • Set <aop:aspectj-autoproxy in the spring configuration file to enable annotation-based AOP
Annotation-based AOP case

<!--注解组件扫描,扫描指定的基本包及其子包下的类,识别使用@Component注解-->
    <context:component-scan base-package="com.imooc"></context:component-scan>
<!--    开启基于注解的AOP-->
    <aop:aspectj-autoproxy/>
package com.imooc.aop.BETalkPoxy;

//1. 定义目标接口
public interface Employee {
    
    
    void talkToBoss();
}


------------------------------------------------
package com.imooc.aop.BETalkPoxy;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

//2.定义目标接口的实现类
@Component
public class EmployeeImpl implements Employee{
    
    
    public void talkToBoss() {
    
    
        System.out.println("我说员工,和老板说话了");
    }
}

--------------------------------------------------------
package com.imooc.aop.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
//3.定义切面
//日志切面  @component组件类 @Aspect 切面类标识
@Component
@Aspect
public class LoggingAspect {
    
    

    //定位到目标对象某一个方法中 public void方法的返回类型
    @Before("execution(public void com.imooc.aop.BETalkPoxy.EmployeeImpl.talkToBoss())")
    public void beforeAdviceMethod(){
    
    
        System.out.println("LoggingAspect 前置通知 记录日志开启");
    }
}


---------------------------------------------
//4.测试

package com.imooc.test;

import com.imooc.aop.BETalkPoxy.Employee;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmployeeAopTest {
    
    

    public static void main(String[] args) {
    
    

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

        Employee bean = (Employee) context.getBean(Employee.class);
        bean.talkToBoss();
    }

}

insert image description here

4. SpringMVC

https://blog.csdn.net/meini32/article/details/132545058

5. SSM

https://blog.csdn.net/meini32/article/details/132569931

Guess you like

Origin blog.csdn.net/meini32/article/details/132474555