Seven components of Spring

1. Seven components of Springimage-20200821075431512

1. Core container (Spring core)

    Spring-core is equivalent to a container that creates and manages beans:

  • Creation: The bottom layer uses reflection technology to create instances of beans;
  • Management: for each bean in the container, the spring container is managed in a singleton mode by default;
  • Design: Use the factory design pattern (BeanFactory).

    The core container provides the basic functionality of the Spring framework. Spring organizes and manages various components and their relationships in Java applications in the form of beans. Spring uses BeanFactory to generate and manage beans, which is an implementation of the factory pattern. The BeanFactory uses the Inversion of Control (IOC) pattern to separate the application's configuration and dependency specification from the actual application code. BeanFactory uses dependency injection to provide component dependencies.

2. Spring context (Spring context)

    A Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internationalization, validation and scheduling functions.

2.1 What does spring context include?

mainly include:

  • DefaultListableBeanFactory
    This is the ioc container that everyone often says, there are many maps and lists in it. The bean of singleton type created by spring for us is stored in one of the maps. The listener (ApplicationListener) we defined is also put into a Set collection.
  • BeanDefinitionRegistry
    puts a BeanDefinition into beanDefinitionMap.
  • AnnotatedBeanDefinitionReader
    for AnnotationConfigApplicationContext. A BeanDefinition reader.
  • Extension point collection
    Stores the list collection of spring extension points (mainly BeanFactoryPostProcessor, BeanPostProcessor) interfaces.

2.2 What is the life cycle of spring context?

 public static void main(String[] args) {
     // 初始化和启动
     AnnotationConfigApplicationContext acaContext = new AnnotationConfigApplicationContext(AppConfig.class);
     // 运行
     acaContext.getBean(ServiceA.class);
     // 关闭/销毁
     acaContext.close();
 }

3. Spring aspect-oriented programming (Spring AOP)

3.1 What is AOP?

    OOP (Object-Oriented Programming) object-oriented programming allows developers to define vertical relationships, but it is not suitable for defining horizontal relationships, resulting in a lot of code duplication, which is not conducive to the reuse of various modules.

    AOP (Aspect-Oriented Programming), commonly known as aspect-oriented programming, as a supplement to object-oriented, is used to extract and encapsulate public behaviors and logic that have nothing to do with business but affect multiple objects into one A reusable module, this module is named "Aspect", which reduces the duplication of code in the system, reduces the coupling between modules, and improves the maintainability of the system. Can be used for authority authentication, logging, transaction processing, etc.

3.2 The role and advantages of AOP

Function: During the running of the program, the function of the method is enhanced without modifying the source code;

Advantages: reduce duplication of code, improve development efficiency, and facilitate maintenance.

3.3 AOP related concepts

Target (target object): the target object of the proxy;

Proxy (proxy): After a class is enhanced by AOP weaving, a resulting proxy class is generated;

Joinpoint (connection point): The so-called connection point refers to those points that are intercepted. In spring, these points refer to methods, because spring only supports method-type join points (methods that can be enhanced);

Pointcut (entry point): The so-called entry point refers to the definition of which Joinpoints we want to intercept (the method that is really enhanced);

Advice (notification/enhancement): The so-called advice means that what you need to do after intercepting the Joinpoint is to notify (the method of enhancing the target method);

Aspect (aspect): It is a combination of entry point and notification (introduction);

Weaving (weaving): refers to the process of applying enhancements to target objects to create new proxy objects. Spring uses dynamic proxy weaving, while AspectJ uses compile-time weaving and class loading-time weaving (the process of combining entry points and enhancements):

Compile time: Aspects are woven in when the target class is compiled. AspectJ's weaving compiler weaves aspects in this way;
class loading period: aspects are woven when the target class is loaded into the JVM. Special class loaders are required, which enhance the bytecode of a target class before it is brought into the application. AspectJ5's load-time weaving supports weaving aspects in this way;
runtime: aspects are woven at a certain point in the application's runtime. Generally, when weaving an aspect, the AOP container will dynamically create a proxy object for the target object. Spring AOP weaves aspects in this way.

3.4 What is the difference between Spring AOP and AspectJ AOP? What are the implementations of AOP?

    The key to AOP implementation lies in the proxy mode. AOP proxy is mainly divided into static proxy and dynamic proxy. Static proxy is represented by AspectJ; dynamic proxy is represented by Spring AOP.

(1) AspectJ is an enhancement of static proxy. The so-called static proxy means that the AOP framework will generate AOP proxy classes during the compilation phase, so it is also called compile-time enhancement. It will weave AspectJ (section) into Java bytes during the compilation phase. In the code, it is the enhanced AOP object when it is running.

(2) The dynamic proxy used by Spring AOP. The so-called dynamic proxy means that the AOP framework will not modify the bytecode, but will temporarily generate an AOP object for the method in memory each time it runs. This AOP object contains the target object. All the methods of , and have enhanced processing at specific cut points, and call back the method of the original object.

3.5 The underlying implementation of AOP

    In fact, the bottom layer of AOP is realized through the dynamic proxy technology provided by Spring. During operation, Spring dynamically generates proxy objects through dynamic proxy technology. When the proxy object method is executed, the enhancement function is intervened, and the method of the target object is called to complete the function enhancement.

3.6 The difference between JDK dynamic proxy and CGLIB dynamic proxy

    There are two main ways of dynamic proxy in Spring AOP, JDK dynamic proxy and CGLIB dynamic proxy:

    JDK dynamic proxies only provide proxies for interfaces and do not support proxies for classes. The core InvocationHandler interface and Proxy class, InvocationHandler calls the code in the target class through the reflection of the invoke() method, and dynamically weaves the cross-cutting logic and business together; then, Proxy uses InvocationHandler to dynamically create an instance that conforms to a certain interface, Generate a proxy object of the target class.
    If the proxy class does not implement the InvocationHandler interface, then Spring AOP will choose to use CGLIB to dynamically proxy the target class. CGLIB (Code Generation Library) is a class library for code generation, which can dynamically generate a subclass object of a specified class at runtime, and override specific methods and add enhanced codes to achieve AOP. CGLIB is a dynamic proxy through inheritance, so if a class is marked as final, it cannot use CGLIB as a dynamic proxy.
The difference between static proxy and dynamic proxy is that the timing of generating AOP proxy objects is different. Relatively speaking, AspectJ's static proxy method has better performance, but AspectJ requires a specific compiler for processing, while Spring AOP does not require specific compiler processing.

    InvocationHandler's invoke(Object proxy, Method method, Object[] args): proxy is the final generated proxy instance; method is a specific method of the proxy target instance; args is the specific input parameter of a method of the proxy target instance, Used when method reflection is invoked.

3.7 AOP Development Explicit Items

1) What needs to be written
Write the core business code (the target method of the target class);

Write the aspect class, and there are notifications (enhanced function methods) in the aspect class;

In the configuration file, configure the weaving relationship, that is, which notifications are combined with which join points.

2) The content of AOP technology implementation
The Spring framework monitors the execution of the entry point method. Once it is monitored that the entry point method is executed, use the proxy mechanism to dynamically create the proxy object of the target object. According to the notification category, weave the corresponding function of the notification into the corresponding position of the proxy object to complete the complete code logic operation.

3) Which proxy method is used at the bottom layer of AOP
In spring, the framework will decide which dynamic proxy method to use according to whether the target class implements the interface.
 

4. Spring DAO module

    The main purpose of the DAO pattern is to isolate persistence-related issues from general business rules and workflows. DAO in Spring provides a consistent way to access the database, regardless of the persistence technology used, Spring provides a consistent programming model. Spring also provides a consistent DAO exception hierarchy for different persistence layer technologies.

4.1 What is DAO

    DAO (Data Access Object) is an object used to access data. Although in most cases the data is stored in the database, this is not the only option. Data can also be stored in files or LDAP. DAO not only shields the difference in the final medium of data storage, but also shields the difference in specific implementation technologies. Providing the abstraction of the DAO layer can bring some benefits: it is easy to construct mock objects to facilitate the development of unit tests; there will be more choices when using aspects, such as JDK dynamic proxy and CGLib dynamic proxy.


4.2 Contents of Spring DAO

  • Spring provides integrated support for multiple persistence technologies, including Hibernate, MyBatis, JPA, JDO;
  • Spring provides a Spring JDBC framework that simplifies JDBC API operations;
  • Spring has formulated a general exception system for DAO, shielding the exception of specific persistence technology, and decoupling the business layer and specific persistence technology;
  • Spring provides template classes to simplify the use of various persistence technologies.

5. Spring ORM module

    ORM: Object Relational Mapping (ORM) mode is a technology to solve the mismatch between object-oriented and relational databases. Simply put, ORM automatically persists the objects in the program to the relational database by using the metadata describing the mapping between the object and the database. So, how to achieve persistence? A simple solution is to hardcode each possible database access operation with a separate method.

    ORM provides another mode for implementing the persistence layer. It uses mapping metadata to describe the mapping of object relationships, so that ORM middleware can act as a bridge between the business logic layer and the database layer of any application. Typical Java ORM middleware are: Hibernate, ibatis, speedframework.

ORM's methodology is based on three core principles:
  Simplicity: Model data in its most basic form.
  Communicative: The database structure is documented in a language that anyone can understand.
  · Accuracy: Create correctly normalized structures based on the data model.

    Spring integrates well with all major ORM mapping frameworks, including Hibernate, JDO implementations, TopLink, and IBatis SQL Map. Spring provides auxiliary classes such as templates for all these frameworks to achieve a consistent programming style.

6. Spring Web module

    The Web Context module builds on the Application Context module and provides a context for Web-based applications. The Web layer uses the Web layer framework. Optionally, it can be Spring's own MVC framework, or the provided Web framework, such as Struts, Webwork, tapestry, and jsf.

7. Spring MVC framework (Spring WebMVC)

    SpringMVC is a Java-based request-driven lightweight Web framework that implements the MVC design model. It is a follow-up product of SpringFrameWork and has been integrated into Spring Web Flow.

    SpringMVC has become one of the most mainstream MVC frameworks at present, and with the release of Spring3.0, it has completely surpassed Struts2 and become the best MVC framework. It uses a set of annotations to make a simple Java class a controller for processing requests without implementing any interfaces. It also supports RESTful programming style requests.

    The MVC framework is a full-featured MVC implementation for building web applications. Through strategic interfaces, the MVC framework becomes highly configurable. Spring's MVC framework provides a clear division of roles: controller, validator, command object, form object and model object, dispatcher, handler mapper and view resolver. Spring supports a variety of view technologies.

7.1  What is Spring MVC

    SpringMVC is a Spring built-in MVC framework.

     MVC framework, which solves common problems in WEB development (parameter reception, file upload, form validation, internationalization, etc.), and is easy to use and seamlessly integrated with Spring. Support RESTful style URL request. Using a loosely coupled pluggable component structure, it is more scalable and flexible than other MVC frameworks.

7.2  The role of SpringMVC

    MVC mode (Model-View-Controller): Solve the separation of page code and background code.

7.3 Principle of Spring MVC

    Before using SpringMVC, we were using Servlet for web development. However, using Servlet development is relatively complicated in receiving request parameters, data sharing, and page jumping. Servlet is the standard for web development in java. Since springMVC is the encapsulation of servlet, it is obvious that the bottom layer of SpringMVC is Servlet, and SpringMVC is a deep encapsulation of Servlet.

7.4  What is the MVC pattern?

    MVC are: model model (javabean), view view (jsp/img), controller Controller (Action/servlet).

The purpose of C's existence is to ensure the consistency between M and V. When M changes, C can update the new content in M ​​to V.

(1) Original mvc mode

 

(2) MVC developed by WEB

 

7.5  SpringMVC execution process and principle

 SpringMVC execution process:

01、用户发送出请求被前端控制器DispatcherServlet拦截进行处理。
02、DispatcherServlet收到请求调用HandlerMapping(处理器映射器)。
03、HandlerMapping找到具体的处理器(查找xml配置或注解配置),生成处理器对象及处理器拦截器(如果有),再一起返回给DispatcherServlet。
04、DispatcherServlet调用HandlerAdapter(处理器适配器)。
05、HandlerAdapter经过适配调用具体的处理器(Handler/Controller)。
06、Controller执行完成返回ModelAndView对象。
07、HandlerAdapter将Controller执行结果ModelAndView返回给DispatcherServlet。
08、DispatcherServlet将ModelAndView传给ViewReslover(视图解析器)。
09、ViewReslover解析ModelAndView后返回具体View(视图)给DispatcherServlet。
10、DispatcherServlet根据View进行渲染视图(即将模型数据填充至视图中)。
11、DispatcherServlet响应View给用户。

Involved component analysis:

1、前端控制器DispatcherServlet(不需要程序员开发)由框架提供,在web.xml中配置。
作用:接收请求,响应结果,相当于转发器,中央处理器。
 
2、处理器映射器HandlerMapping(不需要程序员开发)由框架提供。
作用:根据请求的url查找Handler(处理器/Controller),可以通过XML和注解方式来映射。
 
3、处理器适配器HandlerAdapter(不需要程序员开发)由框架提供。
作用:按照特定规则(HandlerAdapter要求的规则)去执行Handler中的方法。
 
4、处理器Handler(也称之为Controller,需要程序员开发)
注意:编写Handler时按照HandlerAdapter的要求去做,这样适配器才可以去正确执行Handler。
作用:接受用户请求信息,调用业务方法处理请求,也称之为后端控制器。
 
5、视图解析器ViewResolver(不需要程序员开发)由框架提供。
作用:进行视图解析,把逻辑视图解析成真正的物理视图。 
SpringMVC框架支持多种View视图技术,包括:jstlView、freemarkerView、ThymeleafView等。
 
6、视图View(需要工程师开发)
作用:把数据展现给用户的页面。
View是一个接口,实现类支持不同的View技术(jsp、freemarker、pdf等)。

Guess you like

Origin blog.csdn.net/m0_65260253/article/details/131482745