directory

  • 1. The basic
  • 2. Xml-based configuration of IOC
  • 3. Annotations based configuration of IOC
  • 4. Concepts related to AOP
  • 6. The spring into the order
  • 7. Message monitoring mechanism
  • 8. Behavior of things control and dissemination
  • 9. The Spring source code
  • 10. The Spring lifecycle

1. Technical terms

Jointpoint: A method that can be enhanced in Spring, because spring only supports method type join points. When we enhance an object, its internal methods can be used as access points

Pointcuts: The join points that we need to intercept are defined, specifically the methods we need to intercept called access points

Advice: Advice is something to do after intercepting joinToInt

Notification types: pre-notification, post-notification, exception notification, final notification, surround notification

2. Xml-based Spring AOP

  • Import the beans. XML

    
            
    <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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
    </beans>
    Copy the code

The first step is to configure the classes you need to use

<! Add the service object to the Ioc of srping -->
<bean id="accountService" class="com.ytyt.service.impl.AccountServiceImpl"></bean>
<bean id="logger" class="com.ytyt.utils.Logger"></bean>
Copy the code

Xml-based AOP configuration steps in Spring

Use the AOP :config tag to start the aop configuration. Use the AOP :aspect tag to configure the aspect. The -id attribute provides a unique identifier for the aspect. Use the corresponding tag inside the AOP :aspect tag to configure the type of advice. Our example now is to set the printLog method before the pointcut method executes. Used to specify which method in the Logger class is the pre-notification Pointcut property: Used to specify the pointcut expression that means which methods in the business layer are enhancedCopy the code

Pointcut expressions are written as:

Expression: access modifier return value package name. Package name. Package name... Class name. Method name (parameter list) Public void com. Ytyt. Service. Impl. AccountServiceImpl. SaveAccount () access modifier can omit void Com. Ytyt. Service. Impl. AccountServiceImpl. SaveAccount can use wildcards () returns a value, Said any return value * com. Ytyt. Service. Impl. AccountServiceImpl. SaveAccount () the package name can use wildcards, said any package. But there are a few class package, just need to write a few *. * *. *. *. *. AccountServiceImpl. SaveAccount ()) package name can be used.. Represents the current package and its subpackages * *.. AccountServiceImpl. SaveAccount () the name of the class and method names * *. * can be used to implement the wildcard. *.*() Parameter list: Data type: Basic type Direct write name int Name of the reference type write package. Java.lang. String can use wildcards to represent any type, but must have arguments that can use.. It can be any parameter with or without the parameter. If the parameter has any type, it can be written as * *.. *. * (..) Actual development point expression of the writing: usually cut all the way to the business layer under the implementation class * com itheima. Service. Impl. *. * (..)Copy the code

The configuration of AOP

<aop:config>
    <! -- Configuration section -->
    <aop:aspect id="logAdvice" ref="logger">

        <! Expression: specifies the content of the expression -->
        <aop:pointcut id="pt1" expression="execution(public void com.ytyt.service.impl.AccountServiceImpl.saveAccount())"></aop:pointcut>

        <! Configure the notification type and associate the notification method with the pointcut method.
        <aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before>
        <! -- Final notice -->
        <aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>
        <! -- Exception notification -->
        <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>
        <! Rear - - - >
        <aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>
        
    </aop:aspect>
</aop:config>
Copy the code

Configure Surround notification: XML configure surround notification using the ProceedingJoinPoint method

/** * Circular notification * Problem: * When we configure circular notification, the pointcut method does not execute, but the notification method does. * Analysis: * By comparing the surround notification code in the dynamic proxy, we found that the dynamic proxy's surround notification has an explicit pointcut method call, which our code does not. The Spring framework provides an interface: ProceedingJoinPoint. The interface has a method proceed(), which is equivalent to explicitly calling the pointcut method. * This interface can be used as a method parameter around the notification, and the Spring framework will provide us with an implementation class for this interface to use when the program executes. * * Wrap notification in Spring: * It is a way that the Spring framework gives us to manually control in our code when enhancements are executed.Copy the code

Step 1: Specify the methods in the class that surrounds the notification, and the aspect class, through the XML configuration

<! -- Configure surround notification -->
<aop:config>
    <! -- Configuration section -->
    <aop:aspect id="logAdvice" ref="logger">

        <aop:pointcut id="pt1" expression="execution(public void com.ytyt.service.impl.AccountServiceImpl.saveAccount())"></aop:pointcut>
        <aop:around method="aroundPringLog" pointcut-ref="pt1" ></aop:around>

    </aop:aspect>
</aop:config>
Copy the code

Step 2: Configure the location of the notification in the section method

@Around("execution(* com.itheima.service.impl.*.*(..) )"
public Object aroundPringLog(ProceedingJoinPoint pjp){
    Object rtValue = null;
    try{
        Object[] args = pjp.getArgs();// Get the parameters required to execute the method

        System.out.println(The aroundPringLog method in the Logger class starts logging... The front");

        rtValue = pjp.proceed(args);// Explicitly invoke business layer methods (pointcut methods)

        System.out.println(The aroundPringLog method in the Logger class starts logging... Rear");

        return rtValue;
    }catch (Throwable t){
        System.out.println(The aroundPringLog method in the Logger class starts logging... Abnormal");
        throw new RuntimeException(t);
    }finally {
        System.out.println(The aroundPringLog method in the Logger class starts logging... In the end. ""); }}Copy the code

Annotation-based AOP

Configure in bean.xml the packages that need to be scanned when creating the Spring container, and configure the AOP-enabled annotations


      
<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"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <! -- Configure the package to scan when Spring creates containers -->
    <context:component-scan base-package="com.ytyt"></context:component-scan>

    <! Configure Spring to enable annotation AOP support -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
Copy the code

Annotate the classes you need to use and let them be managed by the Spring container

@Service("accountService")
public class AccountServiceImpl implements IAccountService{
    @Override
    public void saveAccount(a) {
        System.out.println("Save performed"); }}Copy the code

And use Aspect annotations to indicate the Aspect class

Pointcuts are introduced through the pointcut annotation

Then use @before, @after and other tags to configure the section

@Component("logger")
@Aspect   // Indicates that the current class is a faceted class
public class Logger {
    @Pointcut("execution(* com.ytyt.service.impl.*.*(..) )"
    private void pt1(a){}

    /** ** */
    @Before("pt1()")
    public  void beforePrintLog(a){
        System.out.println("Pre notifying the beforePrintLog method in the Logger class to start logging...");
    }

    /** ** after notification */
    @AfterReturning("pt1()")
    public  void afterReturningPrintLog(a){
        System.out.println("Post notifying the Logger class that the afterReturningPrintLog method is logging...");
    }
    /** * Exception notification */
   @AfterThrowing("pt1()")
    public  void afterThrowingPrintLog(a){
        System.out.println("Exception notifying the afterThrowingPrintLog method in the Logger class to start logging...");
    }

    /** * Final notification */
    @After("pt1()")
    public  void afterPrintLog(a){
        System.out.println("Finally notifying the afterPrintLog method in the Logger class to start logging..."); }}Copy the code

Surround notification: Configured via the Around tag

@Around("pt1()")
public Object aroundPringLog(ProceedingJoinPoint pjp){
    Object rtValue = null;
    try{
        Object[] args = pjp.getArgs();// Get the parameters required to execute the method

        System.out.println(The aroundPringLog method in the Logger class starts logging... The front");

        rtValue = pjp.proceed(args);// Explicitly invoke business layer methods (pointcut methods)

        System.out.println(The aroundPringLog method in the Logger class starts logging... Rear");

        return rtValue;
    }catch (Throwable t){
        System.out.println(The aroundPringLog method in the Logger class starts logging... Abnormal");
        throw new RuntimeException(t);
    }finally {
        System.out.println(The aroundPringLog method in the Logger class starts logging... In the end. ""); }}Copy the code