Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the design patterns used in Spring

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

What are the design patterns that will be used in Spring? aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

What design patterns are used in JDK? what design patterns are used in Spring? These two questions are more common in the interview. The length of the article is limited, and I only mentioned the interpretation of design patterns and some source code, the main purpose of which is to review the common design patterns in Spring.

Design Patterns (Design pattern) represents the computer programming practice in object-oriented software development. Different types of design patterns are widely used in the Spring framework. Let's take a look at which design patterns are there.

Inversion of Control (IoC) and dependency injection (DI)

IoC (Inversion of Control) is a very important concept in Spring. It is not a technology, but a decoupling design idea. Its main purpose is to decouple objects with dependencies with the help of "third parties" (IOC containers in Spring) (IOC is easy to manage objects, you can just use them), thus reducing the coupling between code. IOC is a principle, not a pattern, and the following patterns (but not limited to) implement the IoC principle.

Ioc-patterns

The Spring IOC container is like a factory. When we need to create an object, we only need to configure the configuration file / annotations, regardless of how the object is created. The IOC container is responsible for creating objects, connecting them together, configuring them, and processing the entire lifecycle of these objects from creation until they are completely destroyed.

In a real project, if a Service class has hundreds or even thousands of classes as its underlying layer, we need to instantiate the Service, and you may have to figure out the constructors of all the underlying classes of the Service every time, which may drive people crazy. If you use IOC, you just need to configure it and reference it where you need it, which greatly increases the maintainability of the project and reduces the difficulty of development. With regard to the understanding of Spring IOC, it is recommended to take a look at Zhihu's answer: https://www.zhihu.com/question/23277575/answer/169698662, very good.

How to understand the control flip? For example: "object a depends on object b, and must be created by itself when object a needs to use object b. However, when the IOC container is introduced into the system, object an and object b have lost direct contact. At this time, when object a needs to use object b, we can specify IOC container to create an object b to inject into object A." The process in which object an acquires dependent object b changes from active behavior to passive behavior, and control is reversed, which is the origin of control reversal name.

DI (Dependecy Inject, dependency injection) is a design pattern that implements control inversion. Dependency injection is to pass instance variables into an object.

Factory design pattern

Spring uses factory mode to create bean objects through BeanFactory or ApplicationContext.

Comparison of the two:

BeanFactory: delayed injection (injected only when a certain bean is used) takes up less memory and the program starts faster than BeanFactory.

ApplicationContext: when the container starts, create all the bean at once, whether you use it or not. BeanFactory only provides the most basic dependency injection support, ApplicationContext extends BeanFactory, and there are more features besides the functions of BeanFactory, so the average developer will use ApplicationContext more.

Three implementation classes of ApplicationContext:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

ClassPathXmlApplication: treat context files as classpath resources.

FileSystemXmlApplication: loads context definition information from a XML file in the file system.

XmlWebApplicationContext: loads the context definition information from the XML file in the Web system.

Example:

Import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class App {public static void main (String [] args) {ApplicationContext context = new FileSystemXmlApplicationContext ("C:/work/IOC Containers/springframework.applicationcontext/src/main/resources/bean-factory-config.xml"); HelloApplicationContext obj = (HelloApplicationContext) context.getBean ("helloApplicationContext"); obj.getMsg ();}}

Singleton design pattern

In our system, there are some objects that we only need, such as thread pools, caches, dialog boxes, registry, log objects, objects that act as device drivers such as printers, graphics cards, and so on. In fact, there can be only one instance of this kind of object, and if multiple instances are created, it may lead to some problems, such as abnormal behavior of the program, excessive use of resources, or inconsistent results.

Benefits of using singleton mode:

For frequently used objects, the time it takes to create objects can be omitted, which is a considerable overhead for those heavyweight objects.

Due to the reduction in the number of new operations, the frequency of use of system memory will also be reduced, which will reduce GC pressure and shorten GC pause time.

The default scope of bean in Spring is singleton (singleton). In addition to singleton scopes, bean in Spring has the following scopes:

Prototype: a new bean instance is created for each request.

Request: each HTTP request generates a new bean, which is valid only within the current HTTP request.

Session: each HTTP request generates a new bean, which is valid only within the current HTTP session.

Global-session: global session scope, which only makes sense in portlet-based web applications, Spring5 is no longer available. Portlet is a small Java Web plug-in that can generate fragments of semantic code (for example: HTML). They are based on portlet containers and can handle HTTP requests like servlet. However, unlike servlet, each portlet has a different session

How to implement a singleton in Spring:

Xml:

Note: @ Scope (value = "singleton")

Spring implements singleton mode in a special way of implementing singleton registry through ConcurrentHashMap. The core code of the Spring implementation singleton is as follows:

/ / implement singleton registry private final Map singletonObjects = new ConcurrentHashMap (64) through ConcurrentHashMap (thread safety); public Object getSingleton (String beanName, ObjectFactory singletonFactory) {Assert.notNull (beanName, "'beanName' must not be null"); synchronized (this.singletonObjects) {/ / check whether the instance Object singletonObject = this.singletonObjects.get (beanName) exists in the cache If (singletonObject = = null) {/ /... Omitted a lot of code try {singletonObject = singletonFactory.getObject ();} / /. A lot of code has been omitted / / if the instance object does not exist, we register in the singleton registry. AddSingleton (beanName, singletonObject);} return (singletonObject! = NULL_OBJECT? SingletonObject: null);}} / / add objects to the singleton registry protected void addSingleton (String beanName, Object singletonObject) {synchronized (this.singletonObjects) {this.singletonObjects.put (beanName, (singletonObject! = null?) SingletonObject: NULL_OBJECT);}

Agent design pattern

Application of Agent Mode in AOP

AOP (Aspect-Oriented Programming: aspect-oriented programming) can encapsulate the logic or responsibilities (such as transaction processing, log management, access control, etc.) that have nothing to do with business but are jointly invoked by business modules, so as to reduce the repetitive code of the system, reduce the coupling between modules, and is conducive to future scalability and maintainability.

Spring AOP is based on dynamic proxy. If the object to be proxied implements an interface, Spring AOP will use JDK Proxy to create a proxy object. For objects that do not implement the interface, JDK Proxy cannot be used for proxy. In this case, Spring AOP will use Cglib. In this case, Spring AOP will use Cglib to generate a subclass of the proxied object as a proxy, as shown in the following figure:

SpringAOPProcess

Of course, you can also use AspectJ, Spring AOP has integrated AspectJ, AspectJ should be regarded as the most complete AOP framework in the Java ecosystem.

After using AOP, we can abstract some common functions and use them directly where they are needed, which greatly simplifies the amount of code. It is also convenient when we need to add new features, which also improves the scalability of the system. AOP is used in logging functions, transaction management, and so on.

What's the difference between Spring AOP and AspectJ AOP?

Spring AOP is a run-time enhancement, while AspectJ is a compile-time enhancement. Spring AOP is based on Proxying, while AspectJ is based on bytecode operation (Bytecode Manipulation).

Spring AOP has integrated AspectJ, and AspectJ should be the most complete AOP framework in the Java ecosystem. AspectJ is more powerful than Spring AOP, but Spring AOP is relatively simple

If we have fewer sections, there is little difference in performance between the two. However, when there are too many aspects, * choose AspectJ, which is much faster than Spring AOP.

Template method

The template method pattern is a behavioral design pattern that defines the skeleton of an algorithm in operation while delaying some steps to subclasses. The template method enables subclasses to redefine the implementation of some specific steps of an algorithm without changing the structure of the algorithm.

Template method UML diagram

Public abstract class Template {/ / this is our template method public final void TemplateMethod () {PrimitiveOperation1 (); PrimitiveOperation2 (); PrimitiveOperation3 ();} protected void PrimitiveOperation1 () {/ / current class implementation} / / method implemented by quilt subclass protected abstract void PrimitiveOperation2 (); protected abstract void PrimitiveOperation3 () } public class TemplateImpl extends Template {@ Override public void PrimitiveOperation2 () {/ / current class implementation} @ Override public void PrimitiveOperation3 () {/ / current class implementation}}

JdbcTemplate, hibernateTemplate, and other classes in Spring that operate on a database that ends with Template, use the template pattern. In general, we use inheritance to implement the template pattern, but Spring does not use this way, but uses the Callback pattern in conjunction with the template method pattern, which not only achieves the effect of code reuse, but also increases flexibility.

Observer mode

Observer mode is a kind of object behavior model. It represents a dependency between an object and an object, and when an object changes, the object on which the object depends will react. The Spring event-driven model is a classic application of the Observer pattern. The Spring event-driven model is very useful and can decouple our code in many scenarios. For example, we need to update the commodity index every time we add goods, and we can use the observer pattern to solve this problem.

Three roles in Spring event-driven Model

Event role

ApplicationEvent (under the org.springframework.context package) acts as the event, which is an abstract class that inherits java.util.EventObject and implements the java.io.Serializable interface.

The following events exist by default in Spring, all of which are implementations of ApplicationContextEvent (inherited from ApplicationContextEvent):

Events triggered after ContextStartedEvent:ApplicationContext starts

Events triggered after ContextStoppedEvent:ApplicationContext stops

Events triggered after ContextRefreshedEvent:ApplicationContext initialization or refresh completes

Events triggered after ContextClosedEvent:ApplicationContext shuts down.

ApplicationEvent-Subclass

Event listener role

ApplicationListener acts as an event listener, which is an interface in which only an onApplicationEvent () method is defined to handle ApplicationEvent. The source code of the ApplicationListener API class is as follows. You can see the definition of the interface and the events in the interface as long as ApplicationEvent is implemented. Therefore, in Spring, we only need to implement the ApplicationListener interface to implement the onApplicationEvent () method to listen for events.

Package org.springframework.context; import java.util.EventListener; @ FunctionalInterface public interface ApplicationListener extends EventListener {void onApplicationEvent (E var1);}

Event publisher role

ApplicationEventPublisher acts as the publisher of the event, which is also an interface.

@ FunctionalInterface public interface ApplicationEventPublisher {default void publishEvent (ApplicationEvent event) {this.publishEvent ((Object) event);} void publishEvent (Object var1);}

The publishEvent () method of the ApplicationEventPublisher interface is implemented in the AbstractApplicationContext class. If you read the implementation of this method, you will find that the event is actually broadcast through ApplicationEventMulticaster. If there is too much specific content, it will not be analyzed here, and it may be mentioned in a separate article later.

Event flow summary of Spring

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Define an event: implement an inherited from ApplicationEvent and write the corresponding constructor

Define an event listener: implement the ApplicationListener interface and override the onApplicationEvent () method

Publish messages using event publishers: messages can be published through the publishEvent () method of ApplicationEventPublisher.

Example:

/ / define an event that inherits from ApplicationEvent and writes the corresponding constructor public class DemoEvent extends ApplicationEvent {private static final long serialVersionUID = 1L; private String message; public DemoEvent (Object source,String message) {super (source); this.message = message;} public String getMessage () {return message } / / define an event listener, implement the ApplicationListener interface, and override the onApplicationEvent () method @ Component public class DemoListener implements ApplicationListener {/ / use onApplicationEvent to receive the message @ Override public void onApplicationEvent (DemoEvent event) {String msg = event.getMessage (); System.out.println ("the message received is:" + msg);}} / / publish the event, which can be published through the publishEvent () method of ApplicationEventPublisher. @ Component public class DemoPublisher {@ Autowired ApplicationContext applicationContext; public void publish (String message) {/ / publish event applicationContext.publishEvent (new DemoEvent (this, message);}}

When you call the publish () method of DemoPublisher, such as demoPublisher.publish ("Hello"), the console prints out: the message received is: Hello.

Adapter mode

The adapter pattern (Adapter Pattern) converts one interface into another that the customer wants, and the adapter pattern allows classes with incompatible interfaces to work together, aliased as Wrapper.

Adapter pattern in spring AOP

We know that the implementation of Spring AOP is based on the proxy pattern, but the enhancement or Advice of Spring AOP uses the adapter pattern, and the interface associated with it is AdvisorAdapter. The common types of Advice are: BeforeAdvice (pre-notification before target method call), AfterAdvice (post-notification after target method call), AfterReturningAdvice (after target method execution ends, before return), and so on. Each type of Advice (notification) has a corresponding interceptor: MethodBeforeAdviceInterceptor, AfterReturningAdviceAdapter, AfterReturningAdviceInterceptor. Spring predefined notifications are adapted to objects of the type of MethodInterceptor interface (method interceptor) through the corresponding adapter (for example, MethodBeforeAdviceInterceptor is responsible for adapting MethodBeforeAdvice).

Adapter pattern in spring MVC

In Spring MVC, DispatcherServlet calls HandlerMapping according to the request information to parse the corresponding Handler of the request. After parsing to the corresponding Handler (also known as the Controller controller), it is processed by the HandlerAdapter adapter. HandlerAdapter is the desired interface, the specific adapter implementation class is used to adapt the target class, and Controller is the class that needs to be adapted.

Why use the adapter pattern in Spring MVC? There are many kinds of Controller in Spring MVC, and different types of Controller process requests in different ways. If the adapter pattern is not used, DispatcherServlet directly acquires the corresponding type of Controller and needs to make its own judgment, as in the following code:

If (mappedHandler.getHandler () instanceof MultiActionController) {((MultiActionController) mappedHandler.getHandler ()). Xxx} else if (mappedHandler.getHandler () instanceof XXX) {.} else if (...) {.}

If we add another Controller type, we will add another line of judgment statement to the above code, which makes the program difficult to maintain and violates the opening and closing principle in the design pattern-open for extensions and closed for modifications.

Decorator mode

The decorator pattern can dynamically add additional properties or behaviors to the object. The decorator pattern is more flexible than using inheritance. To put it simply, when we need to modify the original function, but we do not want to modify the original code directly, we design a Decorator to cover the original code. In fact, in JDK, there are many places to use the decorator mode, such as the InputStream family, the InputStream class has FileInputStream (read files), BufferedInputStream (increase cache, greatly improve the speed of reading files) and other subclasses extend its function without modifying the InputStream code.

Schematic diagram of decorator pattern

When configuring DataSource in Spring, DataSource may be a different database and data source. Can we dynamically switch different data sources according to the needs of customers without modifying the code of the original class? The decorator mode will be used at this time (I don't quite understand the specific principle myself). The wrapper pattern used in Spring contains either Wrapper or Decorator on the class name. These classes basically add some additional responsibilities to an object dynamically.

What design patterns are used in the Spring framework:

Factory design pattern: Spring uses factory mode to create bean objects through BeanFactory and ApplicationContext.

Agent design pattern: the realization of Spring AOP function.

Singleton design pattern: Bean in Spring is singleton by default.

Template method pattern: jdbcTemplate, hibernateTemplate and other classes in Spring that operate on the database ending with Template, they use the template pattern.

Wrapper design pattern: our project needs to connect to multiple databases, and different customers will access different databases as needed during each visit. This mode allows us to dynamically switch different data sources according to the needs of our customers.

Observer pattern: the Spring event-driven model is a classic application of the Observer pattern.

Adapter pattern: the enhancement or Advice of Spring AOP uses the adapter pattern, and the adapter pattern adaptation Controller is also used in spring MVC.

……

The answers to the questions about the design patterns that will be used in Spring will be shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report