Summary of Interview Questions (6) SSM

十、Spring / Spring MVC

 

90. Why use spring?

 

1 Introduction

 

  • Purpose: To solve the complexity of enterprise application development

  • Function: Use basic JavaBean instead of EJB, and provide more enterprise application functions

  • Scope: any Java application

 

In short, Spring is a lightweight container inversion (IoC) and aspect-oriented (AOP) container framework.

 

2. Lightweight  

 

Spring is lightweight in terms of both size and overhead. The complete Spring framework can be published in a JAR file with a size of more than 1MB. And the processing overhead required by Spring is 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 passively instead of creating or searching for dependent objects by the object itself. You can think of IoC as opposed to JNDI-it's not that the object looks up the dependency from the container, but that the container actively passes the dependency to it without waiting for the object request when the object is initialized.

 

4. Face the cut  

 

Spring provides rich support for aspect-oriented programming, allowing cohesive development by separating application business logic from system-level services (such as auditing and transaction management). Application objects only implement what they are supposed to do-complete the business logic-nothing more. They are not responsible (or even conscious) for 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 of your beans is created. Based on a configurable prototype, your beans can create a A separate instance or a new instance is generated each time it is needed — and how they are related to each other. However, Spring should not be confused with traditional heavyweight EJB containers. They are often bulky and heavy and difficult to use.

 

6. Framework

 

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 many basic functions (transaction management, persistence framework integration, etc.), leaving the development of application logic to you.

 

All of these Spring features allow you to write cleaner, more manageable, and easier to test code. 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 complement and improve OOP (Object-Oriented Programming, object-oriented programming). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to establish an object hierarchy to simulate a collection of public behavior. When we need to introduce public behavior for decentralized objects, OOP is powerless. In other words, OOP allows you to define the relationship from top to bottom, but it is not suitable to define the relationship from left to right. For example, the log function. The log code is often distributed horizontally in all object hierarchies, and has nothing to do with the core functions of the objects it spreads. The same is true for other types of code, such as security, exception handling, and transparent persistence. This irrelevant code scattered everywhere is called cross-cutting code. In OOP design, it leads to a lot of code duplication, which is not conducive to the reuse of various modules.

 

The AOP technology is just the opposite. It uses a technology called "crosscutting" to dissect the inside of the encapsulated object, and encapsulate the public behaviors that affect multiple classes into a reusable module, and name it. "Aspect", that is, the aspect. The so-called "aspect" is simply to encapsulate the logic or responsibility that is not related to the business, but is commonly called by the business module, which is convenient for reducing the repetitive code of the system, reducing the coupling between the modules, and conducive to the future. Operation and maintainability. AOP stands for a horizontal relationship. If "object" is a hollow cylinder, which encapsulates the attributes and behavior of the object; then the aspect-oriented programming method is like a sharp edge, cutting these hollow cylinders To get the news inside. And the cut surface is the so-called "facet". Then it restores these cut planes with its clever hands, leaving no trace.

 

Using "crosscutting" technology, AOP divides the software system into two parts: core concerns and crosscutting concerns. The main process of business processing is the core concern, and the part that is not related to it is the cross-cutting concern. One of the characteristics of cross-cutting concerns is that they often occur at multiple places in the core concerns, but they are basically similar everywhere. Such as authority authentication, log, transaction processing. Aop's role is to separate various concerns in the system, separating core concerns and cross-cutting concerns. As Adam Magee, senior solution architect at Avanade, said, the core idea of ​​AOP is to "separate the business logic in the application from the general services that support it."

 

92. Explain what is ioc?

 

IOC is the abbreviation of Inversion of Control, and most books are translated as "control inversion".

  

In 1996, Michael Mattson first proposed the concept of IOC in an article on exploring object-oriented frameworks. For the basic idea of ​​object-oriented design and programming, we have already talked a lot before, and will not repeat it again. In simple terms, it is to decompose a complex system into cooperating objects. After these object classes are encapsulated, the internal implementation is transparent to the outside. , Which reduces the complexity of solving the problem, and can be flexibly reused and extended.

  

The point raised by IOC theory is roughly this: Decoupling between objects with dependencies is achieved by means of "third parties". As shown below:

 

Figure IOC decoupling process

  

As you can see, due to the introduction of the "third party" in the middle, that is, the IOC container, the four objects A, B, C, and D have no coupling relationship, and the transmission between the gears all depends on the "third party". The control of all objects is handed over to the “third-party” IOC container. Therefore, the IOC container has become the key core of the entire system. It plays a role similar to “adhesive” and bonds all objects in the system Working together, without this "adhesive", objects will lose contact with each other. This is why some people compare the IOC container to "adhesive".

  

Let's do another experiment: remove the IOC container in the middle of the picture above, and then take a look at this system:

 

Figure after removing the IOC container

  

What we see now is all we need to accomplish to realize the entire system. At this time, there is no coupling relationship between the four objects A, B, C, and D, and there is no connection with each other. In this case, when you are implementing A, there is no need to consider B, C, and D at all. The dependencies between objects have been reduced to a minimum. Therefore, if IOC containers can be realized, it will be a wonderful thing for system development. Every member participating in the development only needs to implement their own class, which has nothing to do with others!

    

Let's take a look at why the name IOC is so called? Let's compare:

    

Before the software system introduces the IOC container, as shown in Figure 1, object A depends on object B, so when object A initializes or runs to a certain point, it must actively create object B or use object B that has been created. Whether you create or use Object B, control is in your own hands.

    

After the software system introduces the IOC container, this situation has completely changed. As shown in Figure 3, due to the addition of the IOC container, object A and object B have lost direct contact, so when object A runs to need object B At the time, the IOC container will actively create an object B and inject it where needed by object A.

    

From the comparison before and after, it is not difficult to see that the process of obtaining the dependence of object A from object B changes from active behavior to passive behavior, and the control right is reversed. This is the origin of the name "control reversal".

 

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 core containers, data access / integration, Web, AOP (Aspect-Oriented Programming), tools, messages and test modules as shown in the figure below.

 

 


94. What are the common injection methods of spring?

 

Spring implements IOC (Control Inversion) through DI (Dependency Injection). There are three main injection methods:

 

  1. Constructor injection

  2. setter injection

  3. Annotation-based injection

 

95. Are beans in spring thread-safe?

 

Whether the Bean in the Spring container is thread safe. 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 itself does not have the characteristics of thread safety.

 

96. What kinds of bean scopes does Spring support?

 

When creating a Bean instance through the spring container, not only can the Bean instance be instantiated, 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 Bean defined using singleton

  • prototype: Prototype mode, each time a Bean defined by a prototype is obtained through the getBean method of the container, a new Bean instance will be generated

  • request: For each HTTP request, a Bean defined using request will generate a new instance, that is, each HTTP request will generate a different Bean instance. This scope is only valid when using Spring in a web application

  • session: For each HTTP Session, a new instance is generated using the bean bean milk defined by the session. This scope is also valid only when using Spring in a web application

  • globalsession: For each global HTTP Session, a bean defined using the session will generate a new instance. Typically, it is only valid when using portlet context. This scope is also valid only when using Spring in a web application

 

One of the more commonly used is the singleton and prototype two scopes. For singleton scoped beans, each request for the bean 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 of this id, Spring will create a new Bean instance, and then return to the program. In this case, the Spring container only uses the new keyword to create the Bean instance. Once the creation is successful, the container is not tracking the instance and will not maintain the state of the Bean instance.

 

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

 

97. What are the ways for spring to autowire beans?

 

The Spring container is responsible for creating the beans in the application while coordinating the relationship between these objects by 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 together.

 

98. What are the ways of implementing spring transactions?

 

  1. 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.

  2. Declarative transaction management based on TransactionProxyFactoryBean

  3. Declarative transaction management based on @Transactional

  4. Configure transactions based on Aspectj AOP

 

99. What 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: One transaction reads another transaction's uncommitted update data.

  • 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 inserts a "row of new data" into the table. Then, the user who will operate the first transaction in the future will find that there are still unmodified data rows in the table, as if an illusion has occurred.

  • Non-repeatable read: For example, two identical select statements have been executed in the same transaction. During this transaction, no DDL statements have been executed, but the results obtained are inconsistent, which is non-repeatable read.

 

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

 

Flow chart of Spring MVC operation:

 

 

Spring running process description:

      

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

      

2. DispatcherServlet parses the request URL to obtain the request resource identifier (URI). Then, according to the URI, call HandlerMapping to obtain all related objects (including the Handler object and the interceptor corresponding to the Handler object) configured by the Handler, and finally return it as a HandlerExecutionChain object

      

3. DispatcherServlet selects a suitable HandlerAdapter according to the obtained Handler; (Note: if the HandlerAdapter is successfully obtained, the preHandler (...) method of the interceptor will start to be executed at this time)

       

4. Extract the model data in the Request, fill in the Handler parameters, and start executing the Handler (Controller). In the process of filling in the Handler, according to your configuration, Spring will help you do some additional work:

 

  • HttpMessageConveter: convert the request message (such as Json, XML, etc.) into an object, and convert the object into the specified response information

  • Data conversion: perform data conversion on the request message. If String is converted to Integer, Double, etc.

  • Data rooting: formatting the request message. Such as converting a string into a formatted number or formatted date, etc.

  • Data verification: Verify the validity of data (length, format, etc.), and store the verification result in BindingResult or Error

      

5. After the execution of Handler is completed, return a ModelAndView object to DispatcherServlet;

      

6. According to the returned ModelAndView, select a suitable ViewResolver (must be the ViewResolver that has been registered in the Spring container) and return it to the DispatcherServlet;

      

7. ViewResolver combines Model and View to render the view;

      

8. Return the rendering result to the client.

 

101. What are the components of spring mvc?

 

The core components of Spring MVC:

 

  1. DispatcherServlet: Central controller, forwarding requests to specific control classes

  2. Controller: the controller that specifically handles the request

  3. HandlerMapping: mapping processor, responsible for mapping the mapping strategy when the central processor forwards to the controller

  4. ModelAndView: the data returned by the service layer and the encapsulation class of the view layer

  5. ViewResolver: View resolver, resolve specific views

  6. Interceptors: Interceptors, responsible for intercepting the requests we define and then do the processing work

 

102. What is the role of @RequestMapping?

 

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

 

The RequestMapping annotation has six attributes. Below we will divide her into three categories for explanation.

 

value, method:

 

  • value: Specify the actual address of the request, the specified address can be URI Template mode (will be explained later);

  • method: Specify the requested method type, GET, POST, PUT, DELETE, etc .;

 

consumes,produces

 

  • consumes: Specifies the content type (Content-Type) for processing requests, such as application / json, text / html;

  • produces: specifies the returned content type, and returns only if the specified type is included in the (Accept) type in the request request header;

 

params,headers

 

  • params: Specifies that certain parameter values ​​must be included in the request before this method can process them.

  • headers: The specified request must contain certain specified header values ​​in order for the method to process the request.

 

103. What is the role of @Autowired?

 

"Detailed usage of @Autowired": blog.csdn.net/u013257679/article/details/52295106

 

Thirteen, Mybatis

125. What is the difference between # {} and $ {} in mybatis?

  • # {} Is pre-compilation processing, $ {} is string replacement;

  • When Mybatis is processing # {}, it will replace # {} in sql with a?, And call the set method of PreparedStatement to assign value;

  • When Mybatis processes $ {}, it replaces $ {} with the value of the variable;

  • Using # {} can effectively prevent SQL injection and improve system security.

 

126. How many paging methods does mybatis have?

 

  1. Number page

  2. sql pagination

  3. Interceptor paging

  4. RowBounds pagination

 

128. What is the difference between logical paging and physical paging of mybatis?

 

  • The physical page speed is not necessarily faster than the logical page, and the logical page speed is not necessarily faster than the physical page.

  • Physical paging is always better than logical paging: there is no need to put pressure on the database side to the application side, even if there is an advantage in speed, but other performance advantages are sufficient to make up for this shortcoming.

 

129. Does mybatis support lazy loading? What is the principle of lazy loading?

 

Mybatis only supports lazy loading of association and collection related objects. Association refers to one-to-one, and collection refers to one-to-many query. In the Mybatis configuration file, you can configure whether to enable lazy loading lazyLoadingEnabled = true | false.

 

Its principle is to use CGLIB to create a proxy object of the target object. When calling the target method, enter the interceptor method, such as calling a.getB (). GetName (), the interceptor invoke () method finds that a.getB () is If the value is null, then the sql associated with the pre-saved query associated with the B object will be sent separately, query B, and then call a.setB (b), so the object b attribute of a has the value, and then complete a.getB ( ) .getName () method call. This is the basic principle of lazy loading.

 

Of course, not only Mybatis, almost all of them including Hibernate, the principle of supporting lazy loading is the same.

 

130. Tell me about the first-level cache and second-level cache of mybatis?

 

First-level cache: HashMap local cache based on PerpetualCache, its storage scope is Session, when Session flush or close, all Cache in this Session will be emptied, and the first-level cache is turned on by default.

 

The second-level cache has the same mechanism as the first-level cache. By default, PerpetualCache and HashMap storage are used. The difference is that the storage scope is Mapper (Namespace), and the storage source can be customized, such as Ehcache. By default, the second level cache is not turned on. To turn on the second level cache, the use of the second level cache attribute class needs to implement the Serializable serialization interface (which can be used to save the state of the object), which can be configured in its mapping file.

 

For the cache data update mechanism, after a C / U / D operation is performed in a scope (first-level cache Session / second-level cache Namespaces), the cache in all selects in this scope will be cleared by default.

 

131. What is the difference between mybatis and hibernate?

 

(1) Mybatis and hibernate are different, it is not exactly an ORM framework, because MyBatis requires programmers to write Sql statements themselves.

 

(2) Mybatis directly writes the original ecological SQL, which can strictly control the SQL execution performance and has high flexibility. It is very suitable for software development that does not have high requirements on the relational data model, because the demand for such software changes frequently, but the demand changes require rapid output of results . However, the premise of flexibility is that mybatis cannot achieve database independence. If you need to implement software that supports multiple databases, you need to customize multiple sets of sql mapping files, which requires a lot of work. 

 

(3) Hibernate object / relational mapping ability is strong, and the database has good irrelevance. For software that requires high relational models, if you use hibernate development, you can save a lot of code and improve efficiency. 

 

132. What executors do mybatis have?

 

Mybatis has three basic actuators (Executor):

 

  1. SimpleExecutor : Every time update or select is executed, a Statement object is opened, and the Statement object is closed immediately after use.

  2. ReuseExecutor : execute update or select, use SQL as the key to find the Statement object, use it if it exists, and create it if it doesn't exist. After using it, do not close the Statement object, but put it in the Map for the next use In short, the Statement object is reused.

  3. BatchExecutor : execute update (no select, JDBC batch processing does not support select), add all sql to the batch (addBatch ()), wait for unified execution (executeBatch ()), it caches multiple Statement objects, each Statement objects are all after addBatch () is completed, waiting to execute executeBatch () batch processing one by one. Same as JDBC batch processing.

 

133. What is the implementation principle of mybatis paging plugin?

 

The basic principle of the paging plug-in is to use the plug-in interface provided by Mybatis to implement a custom plug-in, intercept the sql to be executed in the plug-in interception method, and then rewrite the sql, according to the dialect dialect, add the corresponding physical paging statement and physical paging parameters.

 

134. How does mybatis write a custom plug-in?

 

From: blog.csdn.net/qq_30051265/article/details/80266434

 

The Mybatis custom plug-in intercepts the four major objects of Mybatis (Executor, StatementHandler, ParameterHandler, ResultSetHandler). The specific interception methods are: 

  • Executor: method of intercepting the executor (log record) 

  • StatementHandler: intercepts the processing of Sql grammar construction 

  • ParameterHandler: Intercept parameter processing 

  • ResultSetHandler: intercept the processing of result sets 

 

The Mybatis custom plug-in must implement the Interceptor interface:

 

  •  
  •  
  •  
  •  
  •  
public interface Interceptor {    Object intercept(Invocation invocation) throws Throwable;    Object plugin(Object target);    void setProperties(Properties properties);}

 

Intercept method: the specific processing logic method of the interceptor 

plugin method: generate dynamic proxy objects based on signature signatureMap 

setProperties method: Set Properties

Custom plugin demo:

 

  •  
  •  
  •  
  •  
// ExamplePlugin.java@Intercepts({@Signature(  type= Executor.class,  method = "update",  args = {MappedStatement.class,Object.class})})public class ExamplePlugin implements Interceptor {  public Object intercept(Invocation invocation) throws Throwable {  Object target = invocation.getTarget(); //被代理对象  Method method = invocation.getMethod(); //代理方法  Object[] args = invocation.getArgs(); //方法参数  // do something ...... 方法拦截前执行代码块  Object result = invocation.proceed();  // do something .......方法拦截后执行代码块  return result;  }  public Object plugin(Object target) {    return Plugin.wrap(target, this);  }  public void setProperties(Properties properties) {  }}

 

One @Intercepts can be configured with multiple @Signature. The parameters in @Signature are defined as follows: 

  • type: indicates the intercepted class, here is the implementation class of Executor;

  • method: indicates the method of interception, here is the update method of intercepting Executor;

  • args: indicates method parameters.

Published 9 original articles · liked 0 · visits 244

Guess you like

Origin blog.csdn.net/Fabri/article/details/105492315