This is the 20th day of my participation in the First Challenge 2022

Spring

Inversion of control IOC

  • Inversion of control IOC: Inversion of Control
    • Is a decoupling design principle
    • The main goal is to decouple dependent objects with the help of a third party, such as the Spring IOC container, to reduce coupling between code
  • The Spring IOC container:
    • The Spring IOC container is responsible for creating objects, wiring them together, and configuring them. The entire life cycle of these objects is processed from creation until the objects are completely destroyed
    • The Spring IOC container is like a factory
    • When you create an object, all you need to do is configure the configuration file or the annotations, and you don’t need to worry about how the object was created. Okay
  • Example of inversion of control:
    • Object A depends on object B. When object A needs object B, object A must create an instance of object B
    • After the IOC container is introduced, when object A needs to use object B, you can specify the IOC container to create an object B to inject into object A
    • After the IOC container is introduced, the process of object A acquiring object B changes from active behavior to passive behavior
  • To achieve theIOCPrinciples of design patterns:
    • The ServiceLocator pattern ServiceLocator
    • Factory mode Factory
    • AbstractFactory pattern AbstractFactory
    • TemplateMethod pattern TemplateMethod
    • Strategy Model
    • Dependency injection Depedency Inject

Dependency injection DI

  • DI: Dependency Inject
    • Pass an instance variable into an object
    • Inversion of control is a design pattern that implements inversion of control

Factory design pattern Factory

  • The BeanFactory and ApplicationContext classes in the Spring framework use the factory pattern to create Bean objects

BeanFactory

  • Lazy injection, even when a Bean is needed
  • It takes up less memory than ApplicationContext and starts faster

ApplicationContext

  • All beans are created when the container starts
  • In contrast to BeanFactory, which provides only rudimentary dependency injection support. ApplicationContext extends BeanFactory, There is much more to BeanFactory than that, and beans are typically created using the ApplicationContext
  • ApplicationContext’s three implementation classes:
    • ClassPathXmlApplication: Use the context file as a classpath resource
    • FileSystemXmlApplication: from the XML file into the context definition information in the file system
    • XmlWebApplicationContext: load the XML file from the Web system context definition information

Singleton design pattern

  • SpringIn theBeanBy default, the scope of theSingletonthe. SpringIn theBeanYou can also define the following scopes:
    • Prototype: Each request creates a new Bean instance
    • Request: Each HTTP request creates a new Bean instance that is valid only in the current HTTP Request
    • Session: Each HTTP request creates a new Bean instance that is valid only for the current HTTP session
  • Spring implements singleton beans in the following way:
    • XML mode:
    <bean id="bean" 
      class="com.oxford.Bean"
      scope="singleton"/>
    Copy the code
    • Way of annotating:
    @Scope(value="singleton")
    Copy the code
  • Spring’s underlying singleton pattern is implemented by implementing the singleton registry with ConcurrentHashMap:
// Implement the singleton registry with thread-safe concurrentHashMap
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);

public Object getSingleton(String beanName, ObjectFactory
        singletonFactory) {
	Assert.notNull(beanName, "'beanName' must not be null");
	synchronized(this.singletonObjects) {
		// Check if there is an instance in the cache
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null) {...try{ singleton = singletonFactory.getObject(); }...// If the instance object does not exist, the object is registered in the singleton registry
			addSingleton(beanName, singletonObject);
		}
		return(singletonObject ! = NULL_OBJECT ? singletonObject :null); }}protected void addSingleton(String beanName, Object singletonObject) {
	synchronized(this.singletonObjects) {
		this.singletonObjects.put(beanName, (singletonObject ! =null? singletonObject : NULL_OBJECT)); }}Copy the code

Proxy design pattern Proxy

Proxy patterns in AOP

  • Faceted programming AOP: Aspect-Oriented Programming
    • Section-oriented programming can encapsulate logic or business functions that have nothing to do with business, but are called together in business modules, such as transaction management, log management, permission control, etc
    • It helps reduce duplicate code, reduce coupling between modules, and facilitate future-oriented extensibility and maintainability
      • Using AOP can greatly simplify the amount of code by abstracting some of the general functions and using them directly where they are needed
      • The need to add new functions will be easier and more convenient, which can improve the scalability of the system
  • Spring AOPBased on dynamic proxy implementation:
    • The proxy object implements the interface:
      • Spring AOP uses Java dynamic Proxy JDK Proxy to create Proxy objects to perform Proxy operations on objects
    • The proxy object does not implement an interface:
      • Spring AOP uses Cglib Proxy to generate a subclass of the proxied object as a Proxy class for the object’s proxying operations

  • Spring AOP integrates with AspectJ, the most complete AOP framework in Java

AspectJ compared to Spring AOP

AspectJ

  • AspectJ is compile-time enhancement
  • AspectJ is implemented based on Bytecode Manipluation
  • AspectJ performs much better than Spring AOP in more faceted situations

Spring AOP

  • Spring AOP is runtime enhancement
  • Spring AOP is based on Proxy implementation
  • AspectJ is integrated with Spring AOP
  • Spring AOP is relatively simple and has similar performance to AspectJ with fewer cuts

TemplateMethod pattern TemplateMethod

  • Template method pattern:
    • Is a behavioral pattern, based on inheritance code reuse
    • Define an algorithm skeleton for an operation, deferring some implementation steps to subclasses
    • The template approach allows subclasses to redefine the implementation of certain steps of an algorithm without changing the structure of an algorithm

  • SpringIn order toTemplateThe closing class, for examplejdbcTemplateEtc., are using the template method pattern
    • Typically, the template pattern is implemented using inheritance
    • In Spring, the combination of Callback and template method is used, which not only achieves the effect of code reuse, but also increases the flexibility of system

Observer mode

  • Observer mode:
    • Is a pattern of object behavior
    • An object has dependencies between objects. When an object changes, the objects that depend on this object also change
  • SpringThe event-driven model is based on the observer pattern
    • The Spring event-driven model decouples code in many application scenarios
    • For example, the observer pattern can be used when the item index needs to be updated each time an item is added

Spring event-driven model

  • SpringThe event-driven model contains three roles:
    • Event Role
    • The role of event Listener
    • Event Publisher Publisher role

Event role Event

  • ApplicationEvent: org.springframework.context
    • Event role abstract class
    • Inherit java.util.Event and implement java.io.Serializable interface
  • SpringThe following events exist by default in theApplicationContextEvent role Abstract class:
    • ContextStartedEvent:
      • The event that is triggered when ApplicationContext is started
    • ContextStoppedEvent:
      • The event that is triggered when ApplicationContext stops
    • ContextRefreshedEvent:
      • The event that is triggered after the ApplicationContext is initialized or refreshed
    • ContextClosedEvent:
      • The event that is triggered when ApplicationContext is closed

The event Listener role Listener

  • ApplicationListener:
    • Event listener role
    • The ApplicationListener interface defines an onApplicationEvent() method to handle ApplicationEvent. Simply implement the onApplicationEvent() method to do the listening for events
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
	void onApplicationEvent(E event);
}
Copy the code

Event Publisher role Publisher

  • ApplicationEventPublisher:
    • Event publisher role
    • ApplicationEventPublisher interface defines publishEvent () method to launch event, this method is realized in AbstractApplicationContext
    • In AbstractApplicationContext events by ApplicationEventMulticaster broadcast
@FunctionalInterface
public interface ApplicationEventPublisher {
	default void publishEvent(ApplicationEvent event) {
		publishEvent((Object) event);
	}

	void publishEvent(Object event);
}
Copy the code

Spring Event Flow

  • Define an event:
    • Implement an event class that inherits from ApplicationEvent and write out the corresponding constructor
  • Define an event listener:
    • Implement the ApplicationListener interface
    • Override the onApplicationEvent() method
  • Using event publishers to publish messages:
    • Using ApplicationEventPublisher publishEvent () method
    • Override the publishEvent() method to publish a message
  • Spring event model example

Adapter mode Adapter

  • Adapter mode:
    • It is the structural pattern and the origin of various structural patterns
    • Convert an interface to the interface that the caller needs
    • Adapters enable classes with incompatible interfaces to work together. Adapters are also known as wrappers

Adapter patterns in Spring AOP

  • Enhancements and Advice in Spring AOP use the adapter pattern and the interface is AdvisorAdapter
  • The commonly usedAdviceTypes include:
    • BeforeAdvice: Pre-notification. Target method pre-call enhancement
    • AfterAdvice: AfterAdvice. Enhanced after target method invocation
    • AfterReturningAdvice: After execution of the target method ends but before return
  • Each noticeAdviceEach has a corresponding interceptor:
    • BeforeAdvice – MethodBeforeAdviceInterceptor
    • AfterAdvice – MethodAfterAdviceInterceptor
    • AfterReturningAdvice – MethodAfterReturningAdviceInterceptor
  • Spring’s predefined notifications are adapted to objects of interface type MethodInterceptor through the corresponding adapter

The adapter pattern in Spring MVC

  • In Spring MVC,DispatchServlet invokes HanlderMapping according to the request information and parses the Handler corresponding to the request. After the Handler is parsed to the Handler, the HandlerAdapter adaptor processes the request
  • The HandlerAdapter acts as the desired interface, and the specific adapter implementation class ADAPTS to the specific target class. Controller acts as the class that needs to be adapted
  • Requests can be handled differently for many types of Controllers in Spring MVC by using the AdapterHandler

Decorator pattern Decorator

  • Decorator mode:
    • Add additional properties or behaviors to an object dynamically
    • The decorator pattern is more flexible than inheritance
  • Use scenario of decorator mode:
    • When you need to modify existing functionality, but don’t want to modify the existing code directly, you can design a Decorator class outside of the existing code that extends the new functionality without modifying the existing class
  • When configuring a DataSource in Spring, a DataSource can be a different database and DataSource. The decorator pattern is used in order to dynamically switch between different data sources with less modification to the code of the original class
  • Spring classes with wrappers and decorators use the staging pattern, which dynamically adds additional properties or functions to an object

conclusion

  • Design patterns used in the Spring framework:
Design patterns The Spring framework
The factory pattern BeanFactory

ApplicationContext
The singleton pattern In the Spring Bean
The proxy pattern Spring AOP
Template method pattern The Spring class that ends with Template
Observer model Spring event-driven model
Adapter mode AdvisorAdapter in Spring AOP

HandlerAdapter in Spring MVC
Decorator mode Spring has wrappers and classes with decorators