Spring / Spring MVC(十)

90. Why use spring?

1 Introduction

  • Purpose: Solve the complexity of enterprise application development
  • Function: Use basic JavaBean instead of EJB, and provide more enterprise application functions
  • Scope: any Java application

Simply put, Spring is a lightweight inversion of control (IoC) and aspect-oriented (AOP) container framework.

Spring is a layered full-stack lightweight open source framework for JavaSE/EE applications
Insert picture description here

2. Lightweight

Spring is lightweight in terms of size and overhead. The complete Spring framework can be published in a JAR file of only 1MB in size. And the processing overhead required by Spring is also negligible. In addition, Spring is non-intrusive: Typically, objects in Spring applications do not depend on Spring's specific classes.

3. Inversion of Control

Spring promotes loose coupling through a technique called Inversion of Control (IoC). When IoC is applied, other objects that an object depends on will be passed in in a passive way, instead of creating or finding dependent objects by the object itself. You can think of IoC as the opposite of JNDI-it's not that the object finds dependencies from the container, but the container actively passes the dependencies to it when the object is initialized without waiting for the object's request.

4. Face the aspect

Spring provides rich support for aspect-oriented programming, allowing cohesive development by separating application business logic and system-level services (such as auditing and transaction management). Application objects only implement what they are supposed to do-complete business logic-nothing more. They are not responsible (or even aware of) other system-level concerns, such as logging or transaction support.

5. Container

Spring contains and manages the configuration and life cycle of application objects. In this sense, it is a container. You can configure how each bean is created-based on a configurable prototype (prototype), your bean can create one Individual instances or generate a new instance every time you need it-and how they are related to each other. However, Spring should not be confused with traditional heavyweight EJB containers. They are often bulky and bulky and difficult to use.

6.Frame

Spring can configure and combine simple components into complex applications. In Spring, application objects are combined declaratively, typically in an XML file. Spring also provides a lot of basic functions (transaction management, persistence framework integration, etc.), leaving the development of application logic to you.

All of these features of Spring enable you to write code that is cleaner, more manageable, and easier to test. They also provide basic support for various modules in Spring.

91. Explain what is aop?

AOP (Aspect-Oriented Programming, aspect-oriented programming) can be said to be the complement and improvement of OOP (Object-Oriented Programming, object-oriented programming). The core idea of ​​AOP is to "separate the business logic in the application from the general services that support it."

) AOP concept
  • AOP (Aspect Oriented Programming), a programming paradigm , belongs to the category of soft engineering, and guides developers how to organize program structure
  • AOP makes up for the shortcomings of OOP, and develops horizontally based on OOP.
    • uOOP stipulates that the program development takes classes as the main model, and everything is carried out around the object, and the model is constructed first to complete a certain task
    • uAOP program development mainly focuses on the common functions based on OOP development, and everything is carried out around common functions. To complete a task, first construct all common functions that may be encountered (when all functions are developed, there is no distinction between commonality and non-commonality)
  • "AOP Alliance"
1.4) AOP role
  • With the advent of the AOP era, we can start from the standardization and standardization of various industries, and develop all common functions step by step, and finally complete the development of individual business modules and even the overall business system with a combination of functions
  • Goal: Move software development from manual production to semi-automated/full-automated stage, and realize the construction of "plug-in component system structure"
1.5) AOP advantages
  • Improve code reusability
  • Business code coding is more concise
  • Business code maintenance is more efficient
  • Business function expansion is more convenient
AOP related concepts
  • Joinpoint (connection point): just the method
  • Pointcut (entry point): is a way to dig out common features
  • Advice (notification): it is a common function, and finally presented in the form of a method
  • Aspect (section): is the corresponding relationship between the common function and the location of the dig
  • Target (target object): is the object generated by the class corresponding to the method of digging out the function, this kind of object cannot directly complete the final work
  • Weaving: the dynamic process of backfilling the dug out function
  • Proxy: The target object cannot directly complete the work, and it needs to be functionally backfilled, which is achieved by creating a proxy object of the original object
  • Introduction (introduction/introduction): is to add member variables or member methods to the original object out of nothing
AOP development process
  • Development stage (Developer completes)
    • Normal production process
    • Develop non-universal functions into the corresponding target object class, and make the entry point method
    • Develop the common functions independently and make them into notifications
    • In the configuration file, declare the entry point
    • In the configuration file, declare the relationship between the entry point and the notification (including the notification type ), that is, the aspect
  • Operation phase (AOP completed)
    • Spring container loads configuration files and monitors the execution of entry point methods for all configurations
    • When the monitor entry point method is run using a proxy mechanism dynamically create the target object 's proxy object , according to the notification categories , the proxy object corresponding to the position notification function corresponding to weaving , and complete the full run code logic
AOP development method
  • XML way
  • XML+ annotation method
  • Annotation method

92. Explain what is ioc? **

IOC is the abbreviation of Inversion of Control, and most books are translated into "Inversion of Control".

The viewpoint put forward by the IOC theory is roughly as follows: the decoupling between dependent objects is achieved by means of a "third party".

  • IoC (Inversion Of Control) inversion of control, Spring reverse control of the external resources used by the application
  • The resources controlled by Spring are all placed in the Spring container, which is called the IoC container

IoC core interface

Insert picture description here

The difference between FactoryBean and BeanFactory**

  • FactoryBean: Encapsulate the creation process of a single bean
  • BeanFactory: the top-level interface of the Spring container, which defines bean-related acquisition operations

93. What are the main modules of spring? **

The Spring framework has integrated more than 20 modules so far. These modules are mainly divided into the core container, data access/integration, Web, AOP (Aspect Oriented Programming), tools, message and test modules as shown in the figure below.

Insert picture description hereInsert picture description here

94. What are the commonly used injection methods for spring?

Spring implements IOC (Inversion of Control) through DI (Dependency Injection). There are mainly three commonly used injection methods:

  • Constructor injection
  • setter injection
  • Annotation-based injection

95. Are beans in spring thread-safe?

Whether the Bean in the Spring container is thread-safe or not, the container itself does not provide a thread-safety strategy for the Bean. Therefore, it can be said that the Bean in the Spring container does not have thread-safe features, but the specific scope of the Bean should be studied.

96. What scope of beans does spring support?

When a Bean instance is created through the spring container, not only the instantiation of the Bean instance can be completed, but also a specific scope can be specified for the Bean. Spring supports the following five scopes:

  • singleton: Singleton mode, in the entire Spring IoC container, there will be only one instance of the Bean defined using singleton
  • Prototype: prototype mode, each time the Bean defined by prototype is obtained through the getBean method of the container, a new Bean instance will be generated
  • equest: For each HTTP request, the Bean defined by the request will generate a new instance, that is, a different Bean instance will be generated for each HTTP request. This scope is valid only when Spring is used in a web application
  • session: For each HTTP Session, a new instance is generated using the bean milk defined by the session. The same scope is valid only when Spring is used in a web application
  • globalsession: For each global HTTP Session, a new instance will be generated using the Bean defined by the session. Typically, it only works when portlet context is used. The same scope is valid only when Spring is used in a web application

Among them, the two scopes of singleton and prototype are more commonly used. For a singleton-scoped bean, every time you request the bean, you will get the same instance. The container is responsible for tracking the state of the Bean instance, and is responsible for maintaining the life cycle behavior of the Bean instance; if a Bean is set to the prototype scope, each time the program requests the bean with that id, Spring will create a new Bean instance and then return it to the program. In this case, the Spring container only uses the new keyword to create a Bean instance. Once the creation is successful, the container will not track the instance, nor will it maintain the state of the Bean instance.

If you do not specify the scope of the Bean, Spring uses the singleton scope by default. When Java creates a Java instance, it needs to apply for memory; when it destroys the instance, it needs to complete garbage collection. These tasks will all lead to an increase in system overhead. Therefore, the creation and destruction of prototype scope beans are relatively expensive. Once a singleton scoped Bean instance is created successfully, it can be reused. Therefore, unless necessary, try to avoid setting the Bean to prototype scope.

97. What are the ways to automatically assemble beans in spring?

The Spring container is responsible for creating beans in the application and at the same time coordinating the relationship between these objects through ID. As developers, we need to tell Spring which beans to create and how to assemble them together.

There are two ways of bean assembly in spring:

  • Implicit bean discovery mechanism and automatic assembly
  • Display configuration in java code or XML

Of course, these methods can also be used in conjunction.

98. What are the implementation methods of spring transaction?

  • Programmatic transaction management is the only option for POJO-based applications. We need to call beginTransaction(), commit(), rollback() and other transaction management-related methods in the code. This is programmatic transaction management.
  • Declarative transaction management based on TransactionProxyFactoryBean
  • Declarative transaction management based on @Transactional
  • Configure transactions based on Aspectj AOP

99. Tell me about Spring's transaction isolation?

Transaction isolation level refers to the degree of isolation between the modification of data by one transaction and another parallel transaction. When multiple transactions access the same data at the same time, if the necessary isolation mechanism is not adopted, the following problems may occur:

  • Dirty read: A transaction reads the uncommitted update data of another transaction.
  • Phantom read: For example, the first transaction modifies the data in a table, for example, this modification involves "all data rows" in the table. At the same time, the second transaction also modifies the data in this table. This modification is to insert "a new row of data" into the table. Then, the user who operates the first transaction in the future will find that there are still unmodified data rows in the table, as if an illusion occurred.
  • Non-repeatable reading: For example, two identical select statements are executed one after another in the same transaction. During this transaction, no DDL statement has been executed, but the results obtained successively are inconsistent, which is non-repeatable reading.

Dirty read: Allows to read uncommitted information

  • 原因:Read uncommitted

Solution: (table-level read lock)

Non-repeatable read: a single data has changed during the reading process

  • Solution: Repeatable read (row-level write lock)

Phantom read: the data entry has changed during the reading process

  • Solution: Serializable (table-level write lock)

100. Tell me about the running process of spring mvc? **

Spring MVC operation flow chart:

Insert picture description hereSpring mvc running process description:

  1. The user sends a request to the server, and the request is captured by the Spring front-end control Servelt **DispatcherServlet (front controller)**;

  2. DispatcherServlet parses the request URL to obtain the requested resource identifier (URI). Then according to the URI, call **HandlerMapping (processor mapper) to obtain all related objects (including Handler objects and interceptors corresponding to Handler objects) configured by the Handler (processor)**, and finally return in the form of HandlerExecutionChain objects ;

  3. DispatcherServlet (front controller) According to the obtained Handler (processor), select a suitable HandlerAdapter (processor adapter) ; (Note: If the HandlerAdapter (processor adapter) is successfully obtained, the interceptor's preHandler ( …)method)

  4. Extract the model data in the Request, fill in the Handler input parameters, and start executing the Handler (Controller).

    [In the process of filling Handler input parameters, according to your configuration, Spring will help you do some extra work:]

1. HttpMessageConveter: Convert the request message (such as Json, xml and other data) into an object, and convert the object into the specified response information.
2. Data conversion: Data conversion on the request message. For example, String is converted to Integer, Double, etc.
3. Data formatting: data formatting of the request message. Such as converting a string into a formatted number or formatted date, etc.
4. Data verification: Verify the validity of the data (length, format, etc.), and store the verification result in BindingResult or Error

  1. After the Handler is executed, it returns a ModelAndView object to the DispatcherServlet (front controller);
  2. According to the returned ModelAndView, select a suitable ViewResolver (view resolver ) (must be a ViewResolver registered in the Spring container) and return it to DispatcherServlet;
  3. ViewResolver combines Model and View to render the view;
  4. Return the rendering result to the client.
SpringMVC technical architecture diagram

Insert picture description here

  • DispatcherServlet: The front controller is the center of overall process control. It calls other components to process user requests,
    effectively reducing the coupling between components
  • HandlerMapping: processor mapper, responsible for finding the corresponding specific Handler processor according to user request
  • Handler: processor, the core class of business processing, usually written by the developer, describing the specific business
  • HandlAdapter: processor adapter, through which the processor is executed
  • View Resolver: View resolver, which generates View views from the processing results
  • View: View, the final output result, commonly used views such as jsp, html

101. What are the components of spring mvc?

The core components of Spring MVC:

  • DispatcherServlet: The central controller, which forwards the request to a specific control class
  • Controller: The controller that specifically processes the request
  • HandlerMapping: mapping processor, responsible for mapping the mapping strategy when the central processor is forwarded to the controller
  • ModelAndView: The package class of the data returned by the service layer and the view layer
  • ViewResolver: View resolver, resolve specific views
  • Interceptors: Interceptors, responsible for intercepting the requests we define and then processing

102. What is the role of @RequestMapping?

RequestMapping is an annotation used to process request address mapping , which can be used on classes or methods. Used on classes, it means that all methods in the class that respond to requests use this address as the parent path.

The RequestMapping annotation has six attributes. Below we will divide it into three categories for description.

value, method:

  • value: Specify the actual address of the request , the specified address can be in URI Template mode (will be described later);
  • method: Specify the method type of the request , set the request method, GET, POST, PUT, DELETE, etc .;
    consumes, produces
  • consumes: Specify the content type (Content-Type) for processing the request , such as application/json, text/html;
  • produces: specifies the type of content returned, and returns only when the (Accept) type in the request header contains the specified type;

params,headers

  • params: **Set the request parameter conditions,** specify that some parameter values ​​must be included in the request before the method is processed.
  • headers: Set the request message header conditions , specify that the request must contain certain specified header values ​​in order for the method to process the request.
Common attributes
@RequestMapping(
    value="/requestURL3", //设定请求路径,与path属性、 value属性相同
    method = RequestMethod.GET, //设定请求方式
    params = "name", //设定请求参数条件
    headers = "content-type=text/*", //设定请求消息头条件
    consumes = "text/*", //用于指定可以接收的请求正文类型(MIME类型)
    produces = "text/*" //用于指定可以生成的响应正文类型(MIME类型)
)
public String requestURL3() {
    
    
    return "/page.jsp";
}

103. What is the role of @Autowired? **

"@Autowired Usage Details": blog.csdn.net/u013257679/article/details/52295106
@Autowired is an annotation used in JavaBean, in the form of byType, used to inject required external resources into specified fields or methods.

Guess you like

Origin blog.csdn.net/xghchina/article/details/114902948