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 questions about Spring?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "what are the problems about Spring". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the problems about Spring"?

1 Spring core components

To sum up: Spring is a lightweight, non-intrusive control inversion (IoC) and aspect-oriented (AOP) framework.

Spring version JDK version 1.x1.3: the dynamic proxy mechanism is introduced, and the bottom layer of AOP is the dynamic proxy. 2.x1.4: normal upgrade 3.x5: introduce comments. The minimum version of Spring 3 is Java 5. From now on, it is not called 1.x but called x4.x6: an epoch-making version that begins to support functions such as Spring Boot 1.X5.x8:lambda expressions.

PS: at present, the standard configuration for Java development is Spring5 + Spring Boot 2 + JDK 8

1.1 introduction to Spring

Today's Java development is also referred to as Spring development. Spring is the largest framework of Java at present. It makes the existing technology easier to use, promotes good programming habits, and greatly simplifies the development of applications.

Because you think, ah, if we want to implement a certain function, the amount of code is generally fixed, either write it all by ourselves or use the existing excellent framework, and Spring not only provides us with a variety of excellent components, but also provides us with a good code organization logic and business development process specification framework, its main advantages are as follows:

Support for IOC and DI

Spring is a large factory container that can leave all object creation and dependency maintenance to Spring management. Spring factory is used to generate Bean and manage the life cycle of Bean to achieve the design concept of high cohesion and low coupling.

Support for AOP programming

Spring provides aspect-oriented programming, which can easily intercept the permissions of the program, run monitoring and other functions.

Support for declarative transactions

You only need to configure to manage the transaction without manual programming, and we don't need to write any more JDBC operations that have been repeated before.

Convenient program testing

Spring provides support for Junit4, and you can easily test Spring programs through annotations.

Adhesive function

Easy to integrate a variety of excellent frameworks, Spring does not exclude a variety of excellent open source frameworks, its internal provides a variety of excellent frameworks (such as: Struts, Hibernate, MyBatis, Quartz, etc.) direct support.

Reduce the difficulty of using JavaEE API

Spring encapsulates some API (JDBC, JavaMail, remote calls, etc.) which are very difficult to use in JavaEE development. The provision of these API greatly reduces the difficulty of application.

1.2 Spring components

Spring framework exists in sub-modules, except for the core Spring Core Container is a necessary module, other modules are optional, there are about 20 modules.

The Spring framework has many features, which consist of seven well-defined modules.

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

The Spring Core:Spring core, which is the most basic part of the framework, provides IOC and dependency injection DI features.

The Spring Context:Spring context container, which is a subinterface of BeanFactory functionality enhancements.

Spring Web: it provides support for Web application development.

Spring MVC: it aims at the implementation of MVC ideas in Web applications.

Spring DAO: provides an abstraction layer for JDBC, which simplifies JDBC coding and makes the coding more robust.

Spring ORM: it supports integration for popular ORM frameworks, such as Spring + Hibernate, Spring + iBatis, Spring + JDO, etc.

Spring AOP: aspect-oriented programming, which provides a programming implementation compatible with the AOP federation.

2 IOC and AOP

The two topics that Spring can never do without are IOC and AOP, which are the two core knowledge points of Spring. Beginners should not be frightened by the terms IOC, AOP, Aspect, Pointcut and Advisor, which are made up by boring people in order to publish papers.

2.1 IOC

Java is an object-oriented programming language. Generally, an application is made up of business logic developed by a set of objects working together, so how to manage these objects? Abstract factory, factory method design pattern can help us create objects, generator pattern can help us deal with the dependencies between objects, but these require us to create other factory classes, generator classes, and we have to manage these classes. it adds to our burden. If the program can automatically manage the declaration cycle of the object when the object is needed, we no longer have to manage the declaration cycle of the Bean, so it will be decoupled.

Spring put forward an idea: Spring is responsible for controlling the life cycle of objects and the relationship between objects. All classes will register in the Spring container to tell Spring what the class is and what it needs, and then Spring will take the initiative to give you what you want when the system is running properly, and give you to other Bean that needs you. The creation and destruction of all classes are controlled by Spring, that is, the life cycle of an object is no longer controlled by the object that references it, but by Spring. For a specific object, it used to control other objects, but now all objects are controlled by spring, so this is called Inversion of Controller, or dependency injection DI (Dependency Injection).

After knowing the general idea, if you try to implement IOC yourself, you will find that the core is reflection + XML parsing / annotation parsing.

Read XML to get bean related information, class information, attribute value information.

Get the constructor of the target class through the reflection mechanism, call the constructor, and then assign a value to the object.

If you want to follow the source code yourself, you will find that the source entry of IOC is refresh (), which contains 13 functions that provide different functions. The specific process is more complicated. The official account replies to IOC to get the original image.

2.2 Context

The IOC container only provides a space for managing objects. How can we put objects into the container that we need to manage for the container? This involves the application context Context of Spring.

Application context Context:

Based on Core and Beans, it provides a large number of extensions, including internationalization operations (based on JDK), resource loading (based on JDK properties), data validation (data verification mechanism encapsulated by Spring itself), data binding (unique to Spring, parameters in HTTP requests are directly mapped to POJO), and type conversion. ApplicationContext interface is the core of Context, which can be understood as the context or background information of Bean.

It is easy to understand that application context is an abstract representation of Spring containers, and our common ApplicationContext is essentially a high-level interface that maintains Bean definitions and collaborative relationships between objects. The Spring framework itself provides implementations of many containers, which are roughly divided into two types:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

One is the less commonly used BeanFactory, which is the simplest container and can only provide basic DI functionality.

The other is the application context derived from BeanFactory, whose abstract interface is the ApplicationContext mentioned above, which can provide more enterprise services, such as parsing configuration text information, etc., which is also the most common application scenario for application context instance objects. With context objects, we can register objects that need to be managed by Spring with the container. For context abstraction interfaces, Spring also provides us with various types of container implementations for us to choose from in different application scenarios.

AnnotationConfigApplicationContext: loads context definitions from one or more java-based configuration classes, suitable for java annotations.

ClassPathXmlApplicationContext: loads context definitions from one or more xml configuration files under the classpath, applicable to the way xml is configured.

FileSystemXmlApplicationContext: loads the context definition from one or more xml configuration files under the file system, that is, the xml configuration file in the system drive letter.

AnnotationConfigWebApplicationContext: specially prepared for web applications, suitable for annotation.

XmlWebApplicationContext: loads the context definition from one or more xml configuration files under the web application, which is suitable for xml configuration.

Work through XML configuration or annotations to manage the cooperation between Bean and Bean configuration, and then use the application context object Context loaded into the Spring container, the container can provide your program with the object management services you want. For example, trace the underlying source code of ClassPathXmlApplicationContext:

You can see that the parsing of a XML file can be extended to 8 layers, which shows that the Spring container has made a comprehensive consideration in order to implement IOC.

2.3 AOP

If we want to code to achieve calculator function, our goal is to achieve addition, subtraction, multiplication and division, but how to print logs and check digital compliance before and after each operation.

Separate the reusable functional modules of logging and data validation, and then dynamically implant and execute the code in the appropriate place for the execution of the program. This simplifies the writing of code.

There is no reference and general logic code in the business logic code, and the business module is more concise and contains only the core business code. The code separation of business logic and general logic is realized, which is easy to maintain and upgrade, and reduces the coupling of business logic and general logic.

Picture idea: the code will eventually be loaded into memory to achieve new out of the object, so if we extract the reusable functions, and then these general functions in memory through the way to construct a new target object will not be OK!

Spring AOP (Aspect Oriented Programming) just provides to consider the program structure from another point of view to improve object-oriented programming. If the purpose of dependency injection is to keep the components that cooperate with each other in a loosely coupled state, AOP is to separate the functions throughout the application to form reusable components. A technique for dynamically adding functionality to a program during compilation, loading, or running without modifying the source code. In order to achieve the isolation of business logic and improve the modularization ability of the code.

In fact, the core of AOP is dynamic proxy, if the interface is implemented, JDK dynamic proxy will be used, otherwise, CGLIB proxy will be used to deal with some system-level services with crosscutting nature, such as log collection, transaction management, security check, cache, object pool management and so on.

Spring mainly provides Aspect aspects, JoinPoint connection points, PointCut pointcuts, Advice enhancements and other implementation methods. AOP generally has five wrapping methods:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Advance notice (@ Before)

Return notification (@ AfterReturning)

Exception notification (@ AfterThrowing)

Post notification (@ After)

Surround notification (@ Around): (highest priority)

PS: in the case of multiple aspects, you can specify the order through @ Order. The smaller the number, the higher the priority.

3 the difference between JDK dynamic agent and CGLIB agent

Both JDK dynamic agent and CGLib dynamic agent are the basis of implementing Spring AOP, and their implementation methods are different.

3.1 JDK dynamic Agent

Characteristics

Interface: for JDK dynamic agents, the business class requires an Interface.

The Proxy:Proxy class is generated dynamically, and after calling the Proxy.newProxyInstance () method, it produces an instance of the Proxy class. In fact, this Proxy class also exists, not just an instance of the class, the Proxy class can be saved on the hard disk.

Method: for each method of the business delegate class, it is now not statically displayed in the Proxy class.

InvocationHandler: this class calls the invoke method first when the business delegates the class to execute. The invoke method is performing the desired proxy operation and can repackage the business method.

Summary:

The JDK dynamic proxy class implements the InvocationHandler interface and overrides the invoke method.

The JDK dynamic proxy is based on the reflection mechanism (method.invoke (objects, parameters)) Proxy.newProxyInstance ()

3.2 CGLib dynamic proxy

Features:

Using bytecode processing framework ASM, its principle is to create a subclass for a class through bytecode technology, and intercept the calls of all parent methods in the subclass by method interception, and weave crosscutting logic into the subclass.

The performance of the dynamic proxy object created by CGLib is much higher than that of the dynamic proxy object created by JDK, but CGLib spends much more time than JDK in creating the proxy object, so for singleton objects, it is appropriate to use CGLib because there is no need to create objects frequently, on the contrary, it is more appropriate to use JDK. At the same time, because CGLib adopts the method of dynamically creating subclasses, it is impossible to proxy the final method.

Note:

The dynamic proxy of JDK can only complete the operation for the interface, while CGlib can do proxy for the class that does not implement the interface as well as for the class that implements the interface.

3.3 Code implementation part

Common code:

/ / Interface class public interface FoodService {public void makeNoodle (); public void makeChicken ();} / / implement interface public class FoodServiceImpl implements FoodService {@ Override public void makeNoodle () {System.out.println ("make noodle");} @ Override public void makeChicken () {System.out.println ("makeChicken");}}

Jdk dynamic proxy code:

Import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class JDKProxyFactory implements InvocationHandler {private Object target; public JDKProxyFactory (Object target) {super (); this.target = target;} / / create proxy object public Object createProxy () {/ / 1. Get the class loader of the target object ClassLoader classLoader = target.getClass (). GetClassLoader (); / / 2. Get the implementation interface of the target object Class [] interfaces = target.getClass (). GetInterfaces (); / / 3. The third parameter requires an object that implements the invocationHandler interface Object newProxyInstance = Proxy.newProxyInstance (classLoader, interfaces, this); return newProxyInstance;} / / the first parameter: proxy object. Generally not used; second parameter: method to be enhanced; third parameter: parameter @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {System.out.println ("this is before the enhanced method."); Object invoke = method.invoke (target, args); System.out.println ("this is after the enhanced method."); return invoke } public static void main (String [] args) {/ / 1. Create the object FoodServiceImpl foodService = new FoodServiceImpl (); / / 2. Create a proxy object JDKProxyFactory proxy = new JDKProxyFactory (foodService); / / 3. Call the enhanced method of the proxy object to get the enhanced object FoodService createProxy = (FoodService) proxy.createProxy (); createProxy.makeChicken ();}}

Cglib dynamic proxy code:

Import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; public class CglibProxyFactory implements MethodInterceptor {/ / get the target object private Object target; / / use the construction method to pass the target object public CglibProxyFactory (Object target) {super (); this.target = target } / / create a proxy object public Object createProxy () {/ / 1. Create Enhancer Enhancer enhancer = new Enhancer (); / / 2. Pass the class enhancer.setSuperclass (target.getClass ()) of the target object; / / 3. Set callback operation enhancer.setCallback (this); return enhancer.create ();} / / Parameter 1: proxy object; Parameter 2: method to be enhanced; Parameter 3: parameter to be enhanced Parameter 4: proxy @ Override public Object intercept (Object proxy, Method method, Object [] args, MethodProxy methodProxy) throws Throwable {System.out.println ("this is before the enhanced method."); Object invoke = methodProxy.invoke (target, args); System.out.println ("this is after the enhanced method."); return invoke } public static void main (String [] args) {/ / 1. Create the object FoodServiceImpl foodService = new FoodServiceImpl (); / / 2. Create a proxy object CglibProxyFactory proxy = new CglibProxyFactory (foodService); / / 3. Call the enhanced method of the proxy object to get the enhanced object FoodService createProxy = (FoodService) proxy.createProxy (); createProxy.makeChicken ();}}

4. The difference between Spring AOP and AspectJ AOP

4.1 Spring AOP

Spring AOP is a runtime enhancement and has the following main features:

Based on dynamic proxy, the default is to use the dynamic proxy provided by JDK if the interface is used, and to use CGLIB if it is a method

Spring AOP needs to be managed by the IOC container, and can only work on the Spring container, implemented in pure Java code

In terms of performance, because Spring AOP is based on dynamic proxy, proxy instances need to be generated when the container is started, and the depth of the stack will be increased on method calls, so the performance of Spring AOP is not as good as that of AspectJ.

Spring AOP is committed to solving the most common AOP (method weaving) in enterprise-level development.

4.2 AspectJ

AspectJ is an easy-to-use and powerful AOP framework, which is enhanced at compile time and can be used alone or integrated into other frameworks. It is a complete solution for AOP programming. AspectJ requires a separate compiler, ajc.

AspectJ belongs to static weaving, which is realized by modifying the code, and the weaving is completed before it is actually run, so the classes it generates have no additional runtime overhead, and generally have the following opportunities for weaving:

Compile-time weaving (Compile-time weaving): if class A uses AspectJ to add an attribute and class B references it, this scenario needs to be woven at compile time, otherwise class B cannot be compiled.

Compiled weaving (Post-compile weaving): that is, .class files have been generated, or have been packed into jar packages. In this case, if we need to enhance processing, we need to use compiled weaving.

Load-time weaving after class loading: refers to weaving when the class is loaded, and there are several common ways to achieve weaving during this period

4.3 comparison

The implementation of Spring AOPAspectJ in pure Java using the Java programming language extension to implement the compiler javac generally requires that ajc can only be woven at run time to support compile-time, post-compile, load-time weaving and only support method-level weavable fields, methods, constructors, Static initial values, etc., can only be implemented on spring-managed Bean, and can be implemented on all domain object implementations. Only method execution is supported for pointcuts. All pointcuts are slower than AspectJ, much faster than AOP, and are easy to learn to use more complex proxies than AOP to create by target objects. Before the aspect application executes the program on the agent, all aspects are directly woven into the code.

5. BeanFactory and FactoryBean

5.1 BeanFactory

BeanFactory ends with Factory, indicating that it is a factory class (interface), and BeanFacotry is the more primitive Factory in Spring.

BeanFactory cannot support many plug-ins of Spring, such as AOP functions, Web applications and so on. ApplicationContext interface is derived from BeanFactory interface, which provides many functions such as international access, event propagation and so on.

BeanFactory is the core of the IOC container and is responsible for producing and managing Bean objects.

5.2 FactoryBean

FactoryBean ends with Bean, indicating that it is a Bean.

FactoryBean is a factory class interface that users can implement to customize the logic of instantiating Bean. The FactoryBean interface occupies an important position for the Spring framework, and Spring itself provides more than 70 FactoryBean implementations.

When Bean in the IOC container implements FactoryBean, the Bean object obtained through getBean (String BeanName) is not the implementation class object of FactoryBean, but the object returned by the getObject () method in the implementation class. To get the implementation class of FactoryBean, you need getBean (String & BeanName), preceded by BeanName with &.

6. Spring life cycle

The process of Spring IOC initialization and destruction of Bean is roughly divided into four parts: Bean definition, Bean initialization, Bean lifetime and Bean destruction.

If only instantiation and dependency injection are easy, the problem is that if we want to complete the custom requirements, Spring provides a series of interfaces and configurations to complete the Bean initialization process. Take a look at the entire IOC container initialization Bean process.

In general, we customize the initialization and destruction of Bean in the following three ways:

1. Configure via XML or @ Bean

This is done through xml or @ Bean (initMethod= "init", destroyMethod= "destory").

two。 Using two annotations defined by JSR250 rules (java specification) to implement

@ PostConstruct: initializes the Bean after it is created and belongs to the assignment, which belongs to the annotation of the JDK specification.

PreDestroy: notify before the bean will be removed and clean up before the container is destroyed.

Tip: JSR is a set of specifications provided by JDK.

3. Implement class methods through inheritance

Implement the afterPropertiesSet () method of the InitializingBean interface, which is called when beanFactory creates the object and sets all the properties of the bean, which is equivalent to the initialization method.

Implement the destory () method of DisposableBean. When the bean is terminated, the single instance bean is destroyed.

For a single instance of bean, the initialization and destruction methods can be called normally. For multi-instance bean, the container is only responsible for initializing when calling, but does not manage bean, and the termination method is not called when the container is closed.

7. Design patterns in Spring

Different types of design patterns are widely used in the Spring framework. Let's take a look at which design patterns are there.

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.

8. Spring circular dependency

8.1 brief introduction of circular dependence

Spring circular dependency: to put it bluntly, there is a direct or indirect dependency between one or more object instances, which constitutes a circular call. The two prerequisites for circular dependency are:

The Bean that has circular dependencies must be a singleton (singleton). If you rely on prototype, you will not have this requirement at all.

The way of dependency injection can not all be the way of constructor injection, it can only solve the circular dependency of setter method, which is wrong.

Assuming that AB depend on each other, the following conclusions can be drawn after trying different injection methods:

The problem of dependency injection to solve the problem of AB cyclic dependency is to use setter method to inject attributes automatically for AB cyclic dependencies is to use constructor injection no to inject B into AB cyclic dependency An is setter method, the way to inject An in B is to inject An in AB cyclic dependency B is setter method, and the way to inject B in An is constructor No.

PS: the fourth can and the fifth can not is that Spring is created by default according to the natural order when creating a Bean, so A will create it before B.

8.2 popular theory of circular dependence

Spring solves circular dependencies through three levels of caching.

First-level cache: Map singletonObjects, singleton pool, used to hold instantiated, injected, initialized bean instances

Secondary cache: Map earlySingletonObjects, an early exposure object, used to hold the instantiated bean instance

Three-tier cache: Map

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