SSM framework-Spring framework core knowledge review

 

Table of contents

1. SpringIoC

1.1 Understand the SpringIoC container

1.2 Configure SpringIoC container based on xml

1.3 Bean life cycle and scope based on xml configuration

1.4 Configure SpringIoC container based on xml and annotations

1.5 Configure SpringIoc container based on fully annotated classes

2. SpringAop face-to-face programming

2.1 Understanding SpringAop aspect-oriented programming

2.2SpringAop is based on annotation configuration

2.3 Notification annotations

3. Spring-Tx transaction

3.1Spring-Tx transaction


The core content of the Spring framework is divided into three parts

They are SpringIoC container, SpringAop aspect-oriented programming, and SpringTx transactions. The following will introduce the relevant knowledge of the corresponding core content respectively.


1. SpringIoC

1.1 Understand the SpringIoC container

Original text: Understanding the SpringIOC container_Alphamilk's blog-CSDN blog

core content:

一、Spring Framework

  1. Spring Framework is an open source application framework developed by SpringSource Corporation and was originally created to solve common problems in enterprise development. It provides rich functions, such as dependency injection (DI), aspect-oriented programming (AOP), declarative transaction management, etc., making the development of enterprise-level applications easier and faster.
  2. Spring Framework is the basic implementation in the Spring family, including Spring Cloud, Spring MVC and other technologies are built on the Spring Framework.
  3. Spring Framework has the advantages of rich ecology, modular design and simplified Java development. It continues to innovate and develop, introducing new features and functions to meet the needs of different scenarios.

2. Spring IOC container

  1. The Spring IOC container is a complex container that can manage dependencies between components and is responsible for creating and destroying components. It has more functions and features than ordinary containers.
  2. Components are objects that can be reused. For example, in a three-tier framework, the three-tier architecture can be split into three components.
  3. The advantages of Spring management components include reducing coupling between components, improving code reusability and maintainability, facilitating configuration and management, and providing other functions such as AOP, transaction management, etc.
  4. The core interfaces of the SpringIOC container include BeanFactory and ApplicationContext, where ApplicationContext is an extension of BeanFactory and provides more advanced functions and features.
  5. ApplicationContext has four specific implementation classes, which are suitable for different scenarios and configuration methods, such as ClassPathXmlApplicationContext, FileSystemXmlApplicationContext, AnnotationConfigApplicationContext and WebApplicationContext.

3. Core functions of Spring IOC

  1. The core features of Spring are Spring IOC (Inversion of Control) and DI (Dependency Injection).
  2. Inversion of control (IOC) refers to the transfer of object creation and calling control from the application to the container. The container is responsible for creating and managing objects, and injecting object dependencies into the application through dependency injection.
  3. Dependency injection (DI) is the process of transferring dependencies between components. Dependency processing is handed over to the container to avoid hard-coding dependencies between objects in the application code and achieve decoupling between objects. .
  4. Dependency injection can be implemented in three forms: constructor injection, Setter method injection and interface injection, and is configured through annotations or XML configuration files.
  5. Spring's IOC container and DI functions make component management and configuration more flexible, reusable and maintainable, improving code testability and scalability.

1.2 Configure SpringIoC container based on xml

Original text: Implementing SpringIoC configuration based on XML_Alphamilk's blog-CSDN blog

core

1. Configure Spring IOC based on XML:

  1. Configure the jar package dependencies of Spring IOC.
  2. Write an XML configuration file, define the <bean> tag to represent the component, and configure the component's id and class attributes.
  3. Implement the creation of components, including no-parameter construction method creation, static factory creation and non-static factory creation.

2. XML-based configuration DI (dependency injection):

  1. Constructor-based DI is accomplished by the container calling a constructor with multiple parameters, either using a single-parameter constructor or a multi-parameter constructor.

    • Single-parameter constructor: Use <constructor-arg ref="..." /> in the XML configuration to specify the injected object.
    • Multi-parameter construction method: Use <constructor-arg name="..." value="..." ref="..." /> in the XML configuration to specify the injected parameters.
  2. DI based on the setter function is completed by the container calling the setter method of the component. You can use <property name="..." value="..." ref="..." /> to specify the injected property value or Quote.

3. Create ioc container and obtain components

  1. Create IoC container:

    • You can use ApplicationContextthe implementation class of the interface, for example ClassPathXmlApplicationContext, to create a container object by specifying a configuration file.
    • You can also create ApplicationContexta subclass object first, then set the configuration file path, and call refresh()the method to refresh the container.
  2. Three ways to obtain components through containers:

    • The first way: use getBean()the method and component ID to get the component, return an Objectobject of type, and then convert it to the corresponding type.
    • The second way: Use getBean()the method to specify the type of the component as a parameter and directly return the corresponding type.
    • The third way: directly obtain the component according to its type without specifying the component ID.

1.3 Bean life cycle and scope based on xml configuration

Original text: Advanced features of SpringIoC components_Alphamilk's blog-CSDN blog

 1. Bean life cycle

  1. The life cycle creates the corresponding parameterless method in the corresponding JavaBean class, and adds the init-method and destroy-method attributes in the configuration <bean> tag.

示例:<bean id="beanId" class="com.example.BeanClass" init-method="initMethod" destroy-method="destroyMethod"/>

2. Bean scope

  1. Scope first introduces two types of scope: single instance mode and multiple instance mode.
  1. Singleton mode (Singleton) - The default means that after configuring the <bean> tag, only the same object will be obtained when obtaining the component. The container will only create a unique bean object and will not create new objects.

示例:<bean id="beanId" class="com.example.BeanClass" scope="singleton"/>

  1. Multiple instance mode (Prototype) In the multiple instance mode, after configuring a <bean> component, the container will create a new object each time the component is obtained.

示例:<bean id="beanId" class="com.example.BeanClass" scope="prototype"/>


1.4 Configure SpringIoC container based on xml and annotations

Original text: SpringIoC based on annotation configuration_Alphamilk's blog-CSDN blog

1. Annotation method and scanning (IoC)

  • The annotation method is to use specific annotations to mark components, such as @Component, @Repository, @Service, and @Controller.
  • Scanning means that the Spring container automatically scans the components under the specified package, instantiates and manages them.

2. Introduction to configuration files

  • Configuration files can be used to specify the packages that the component scans, and can include or exclude specific annotations.
  • Ordinary configuration can directly specify the packages to be scanned.
  • Configurations containing annotations can specify packages and scan only components with the specified annotations.
  • Exclude annotation configurations to specify packages and exclude components with specific annotations.
  • The name of a component bean can be set by specifying the name attribute.

3. Component scope and periodic method annotations

  • Cycle methods are methods that are executed in different life cycle stages such as component creation, destruction, and initialization.
  • You can use the @PostConstruct annotation to execute the initialization method after the component is created.
  • You can use the @PreDestroy annotation to execute cleanup methods before the component is destroyed.
  • The scope of a bean can be configured through the @Scope annotation.

4. Reference type automatic assembly (DI)

  • Autowiring means that the Spring container automatically injects dependencies into components.
  • Autowiring can match based on type and inject objects that match the type into the component.
  • The three scenarios of autowiring are byName, byType and constructor autowiring.

5. Basic type attribute assignment (DI)

  • You can set the basic type properties of a component directly through property assignment.
  • You can also use the @Value annotation for attribute assignment.

1.5 Configure SpringIoc container based on fully annotated classes

Original text: Managing Beans based on configuration classes_Alphamilk's blog-CSDN blog

1. Complete annotation development understanding:

  • Fully annotated configuration replaces XML configuration files through Java configuration classes and annotations.
  • Fully annotated configuration has greater type safety and readability.

2. Configuration classes and scanning annotations:

  • Use @Configuration to mark a class as a configuration class, which is used to define Spring beans and configure other components.
  • @PropertySource is used to load external property files into the Spring environment.
  • @ComponentScan is used to specify the basic package to be scanned and register the classes under it as Spring Beans.

3. Two ways to create an IoC container through AnnotationConfigApplicationContext:

  1. Create AnnotationConfigApplicationContext directly and import the configuration class.
  2. After creating an AnnotationConfigApplicationContext instance, call the register method to register the configuration class.

4. @Bean definition component:

  • @Bean is used to declare a method to generate a Bean managed by Spring.
  • The name of the bean can be specified through the name/value attribute.
  • Custom initialization and destruction methods of a Bean can be specified through the initMethod and destroyMethod properties.

5. Details of @Bean annotation:

  • The name of the bean defaults to the method name, and the name can also be specified through @Bean(name="beanName").
  • Bean initialization and destruction methods can be defined by using @PostConstruct and @PreDestroy annotations on the method.
  • You can specify the Bean's initialization and destruction methods through @Bean's initMethod and destroyMethod attributes.
  • The scope of the bean can be specified through the @Scope annotation.

6. Calls between Bean components:

  • You can directly call other Bean methods to obtain the corresponding components.
  • Other components can also be injected through formal parameters.

7. @Import extension:

  • @Import can integrate multiple configuration classes into one configuration class.
  • XML configuration files can be imported using @ImportResource.

2. SpringAop face-to-face programming

2.1 Understanding SpringAop aspect-oriented programming

Original text: Understanding Spring AOP aspect-oriented programming_Alphamilk's blog-CSDN blog

core content:

AOP (Aspect-Oriented Programming) is a programming thinking used to solve the problems of non-core code duplication and difficulty in maintenance in OOP (Object-Oriented Programming). AOP achieves code clarity, simplicity, and ease of maintenance by separating cross-cutting concerns (such as logging, transactions, permission control, etc.) from business logic.

The core concepts of AOP include:

  1. Aspect: Encapsulates common behaviors that have nothing to do with the business, that is, cross-cutting concerns, to facilitate code reuse and reduce coupling between modules.
  2. Advice: implements the specific functions of aspects, such as pre-notification, return notification, exception notification, post-notification and surrounding notification.
  3. Joinpoint: The intercepted method can apply notifications before, after, or when an exception is thrown.
  4. Pointcut: An expression that locates a connection point and specifies the selected connection point.
  5. Target: The target object being proxied.
  6. Proxy: The proxy object generated after applying notification on the target object.
  7. Weaving: The process of applying notifications to targets and generating proxy objects.

The Spring AOP framework is based on the implementation of AOP programming thinking, encapsulates dynamic proxy technology, and simplifies the implementation process of dynamic proxy. With a small amount of configuration and specifying entry points and notification types, aspect-oriented programming can be achieved. Spring AOP can be applied to various scenarios, such as logging, transaction processing, security control, performance monitoring, exception handling, cache control and dynamic proxy, etc., to improve the maintainability and reusability of the code.


2.2SpringAop is based on annotation configuration

Original text: Spring AOP based on annotation implementation and details_Alphamilk's blog-CSDN blog

1. Spring AOP underlying technology:

  1. JDK dynamic proxy: Use the InvocationHandler interface to implement the proxy, and the target class that needs to be proxied must implement the interface.
  2. CGLIB dynamic proxy: implements proxy by inheriting the proxied target class, and does not require the target class to implement the interface.
  3. AspectJ: An early AOP framework, Spring AOP borrows the AOP annotations in AspectJ.

2. AOP programming implementation steps:

  1. Use annotation configuration: @Aspect marks the class as an aspect class and defines the location of aspect logic and enhancement methods; @EnableAspectJAutoProxy turns on AspectJ automatic proxy and enables Spring AOP function.
  2. Import related dependencies: including Spring Aspects, Spring Context, Spring Test, etc.
  3. Define enhancement methods: Use annotation configuration to specify the location of the insertion target, such as @Before, @After, @AfterReturning, @AfterThrowing, @Around, etc.
  4. Completion annotations: Add the enhanced class to the IOC container and set the aspect annotations @Component and @Aspect.
  5. Enable AspectJ annotations: Use the @EnableAspectJAutoProxy annotation in the configuration class to enable annotation support.

3. How to obtain detailed information about cut points:

  1. Use the JoinPoint interface: Through JoinPoint, you can obtain the target object, the class of the target object, the simple class name of the target object, the method parameter array, the method signature and other information.
  2. Parameters of the enhancement method: You can add a parameter of JoinPoint type in the enhancement method, and then obtain the information of the target object through this parameter.

4. Pointcut expression syntax: Pointcut expression syntax includes specific values ​​and fuzzy values, which can be used to define matching rules for pointcuts.

5. Reuse of pointcut expressions:

  1. Extract in the current class: Use the @Pointcut annotation to declare an empty method and add a specific pointcut expression to the method. Other enhancement methods can reuse pointcuts by calling this empty method.
  2. Create a class to store pointcuts: Create a separate class to store pointcuts, and define pointcut expressions through the @Pointcut annotation. Enhancement methods in other classes can reuse pointcuts by referencing methods of the class that stores the pointcuts.

2.3 Notification annotations

Original text: Spring Aop--Notification Annotation_Alphamilk's Blog-CSDN Blog

1. Around annotation: Around annotation (@Around) is a notification type in Spring AOP, which performs surrounding operations before and after the target method is executed. It can add additional logic before and after method calls, such as logging, performance monitoring, etc. Using surrounding annotations requires creating a ProceedingJoinPoint object and controlling the execution flow of the target method through this object inside the method.

advantage:

  1. High flexibility: Additional logic code can be inserted before and after the execution of the target method to fully control the execution process of the method.
  2. Unified processing: Extract common logic codes into aspects to achieve unified processing logic and avoid repeatedly writing the same code in each target method.
  3. The return value can be modified: The final result can be affected by modifying the return value of the target method.

shortcoming:

  1. Increased complexity: Compared with other types of notifications, using surrounding annotations is slightly more complicated and requires more understanding and mastery, especially for the use of ProceedingJoinPoint.
  2. Performance overhead: Because the surrounding annotations will wrap the execution process of the entire target method, it may cause a certain performance overhead in some cases, especially when the processing logic is more complex.
  3. Possible introduction of side effects: When making any modifications to the target method in a surround notification, you need to operate with caution to avoid introducing unpredictable side effects, which may lead to abnormal or abnormal behavior of the program.

2. Priority annotation: Priority annotation (@Order) is an annotation in the Spring framework used to define the loading order of components. Can be used at class level or method level. When multiple components implement the same interface or inherit the same parent class, their loading order can be specified through the @Order annotation. The smaller the @Order value, the higher the priority and the higher the loading order. The loading order of components with the same priority is uncertain, and it is best to set priorities to different values ​​to avoid uncertainty.

Use the @Order annotation to have different enhancements for the same method and specify the execution order of the enhancements.


3. Spring-Tx transaction

3.1Spring-Tx transaction

Original text: Spring-TX Transaction_Alphamilk's Blog-CSDN Blog

core content

1. Types of transaction management:

  1. Programmatic transactions: Manually writing code to manage transactions makes the operation complex.
  2. Declarative transactions: Control transactions through annotations or configuration files, and the code is concise.

2. Use of Spring transaction manager:

  1. Interface: Spring transaction manager is used to manage transactions.
  2. Implementation class: Select the appropriate implementation class according to the persistence layer framework.

3. Use of transaction annotations:

  1. Mark: Used to mark methods or classes that require transaction management.
  2. Properties: including read-only mode, timeout, specified exception and isolation level.

4. Classification of transaction attributes:

  1. Read-only mode: restrict whether the transaction is read-only.
  2. Timeout: Limit transaction execution time.
  3. Specify exception: Specify the exception type for transaction rollback.
  4. Isolation level: Defines the isolation level of the transaction.

5. Transmission properties of transactions:

  1. Define relationships between transactions.
  2. Commonly used attributes are REQUIRED and REQUIRES_NEW.

Guess you like

Origin blog.csdn.net/dogxixi/article/details/132636252