[Knowledge Points for Java Interviews] The most comprehensive test questions with detailed answers to share, don’t worry about reading this interview with major manufacturers!

2020 latest Java collection of common interview questions + detailed answers (8)

The interview questions have been updated to the eighth module. Recently, I am also inquiring about their interview experience with recent partners in major factories, and strive to let everyone know the latest news and collect more comprehensive interview information. If you want to see the first few collections, you can go to my homepage to find them.

Some of the answers are summarized by myself, and some are collected on the Internet. Don't panic after watching these interviews! If you have more experience, you can share it in the comments. If you have any mistakes, you are welcome to point it out. Please let me know, thank you~

Nine, design patterns

69. What is the difference between a simple factory and an abstract factory?

 

Simple factory pattern :

 

The model itself is very simple and used in the case of simple business. Generally used for small projects or when specific products are rarely expanded (so that the factory class does not need to be changed frequently).

 

It consists of three roles:
 

  • Factory role: This is the core of this model, which contains certain business logic and judgment logic. According to different logics, specific factory products are produced. Such as the Driver class in the example.

  • Abstract product role: It is generally a parent class inherited by a specific product or an implemented interface. Realized by interface or abstract class. Such as the Car interface in the example.

  • Specific product role: The object created by the factory class is an instance of this role. It is implemented by a specific class in Java, such as the Benz and Bmw classes in the example.


Let’s use a class diagram to clearly show the relationship between them:


 

Abstract factory pattern:

 

Let's first understand what a product family is: a family of products that are located in different product hierarchical structures and have related functions.

 

 

BmwCar and BenzCar in the figure are two product trees (product hierarchy); and BenzSportsCar and BmwSportsCar as shown in the figure are a product family. They can all be placed in the sports car family, so the functions are related. Similarly, BmwBussinessCar and BenzBusinessCar are also a product family.
 

It can be said that the difference between it and the factory method pattern lies in the complexity of creating objects. And the abstract factory model is the most abstract and general of the three. The purpose of the abstract factory pattern is to provide an interface for the client to create product objects in multiple product families.
 

Moreover, the following conditions must be met to use the abstract factory pattern:
 

  1. There are multiple product families in the system, and the system can only consume one product family at a time

  2. Products that belong to the same product family are used.


Let's take a look at the roles of the abstract factory pattern (the same as the factory method):
 

  • Abstract factory role: This is the core of the factory method pattern, it has nothing to do with the application. It is the interface that the specific factory role must implement or the parent class that must be inherited. It is implemented by abstract classes or interfaces in java.

  • Specific factory role: It contains code related to specific business logic. Called by the application to create the corresponding specific product object. It is implemented by concrete classes in java.

  • Abstract product role: it is the parent class inherited by the concrete product or the interface implemented. Generally there are abstract classes or interfaces to implement in java.

  • Specific product role: The object created by a specific factory role is an instance of this role. It is implemented by specific classes in java.

 

十、Spring / Spring MVC

 

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

 

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 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 finding dependent objects by itself. You can think of IoC as the opposite of JNDI-it's not that the object looks for 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 large and heavy 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 many 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.

 

71. 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). OOP introduces concepts such as encapsulation, inheritance, and polymorphism to establish an object hierarchy to simulate a collection of public behaviors. When we need to introduce public behaviors for scattered objects, OOP is powerless. In other words, OOP allows you to define a relationship from top to bottom, but it is not suitable for defining a relationship from left to right. For example, log function. Logging code is often distributed horizontally in all object levels, and has nothing to do with the core functions of the objects it distributes. The same is true for other types of code, such as security, exception handling, and transparent persistence. This kind of irrelevant code scattered everywhere is called cross-cutting code. In OOP design, it causes 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 "cross-cutting" to dissect the inside of the encapsulated object, and encapsulate the common behaviors that affect multiple classes into a reusable module, and name it For "Aspect", that is, aspect. The so-called "aspect", simply put, is to encapsulate the logic or responsibilities that are not related to the business but are called by the business modules, which is convenient for reducing the repetitive code of the system, reducing the coupling between the modules, and is conducive to future development. Operability and maintainability. AOP represents a horizontal relationship. If the "object" is a hollow cylinder, which encapsulates the properties and behaviors of the object; then the method of aspect-oriented programming is like a sharp edge, cutting these hollow cylinders Open to get the news inside. The cut section is the so-called "aspect". Then it restored these cut planes with ingenious skill, leaving no trace.

 

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

 

72. Explain what is ioc?

 

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

  

In 1996, Michael Mattson first proposed the concept of IOC in an article about object-oriented frameworks. For the basic ideas of object-oriented design and programming, we have already talked a lot before, so I won’t go into details. Simply put, it is to decompose a complex system into mutually cooperating objects. After these object classes are encapsulated, the internal implementation is transparent to the outside. , Thereby reducing the complexity of solving the problem, and can be flexibly reused and extended.

  

The viewpoint put forward by the IOC theory is roughly as follows: the decoupling between dependent objects 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 position, that is, the IOC container, the four objects of A, B, C, and D have no coupling relationship, and the transmission between 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 becomes the key core of the entire system. It acts like a “glue” to glue all objects in the system. To play a role together, if there is no such "adhesive", the object and the object will lose contact with each other. This is the reason why some people compare the IOC container to the "glue".

  

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

 

Picture of the system after removing the IOC container

  

The picture we see now is all the content we need to complete to realize the entire system. At this time, the four objects of A, B, C, and D are no longer coupled and have no connection with each other. In this case, when you are implementing A, you don’t need to think about B, C, and D anymore. The dependencies between objects have been reduced to a minimum. Therefore, if the IOC container can really be realized, it will be a wonderful thing for system development. Every member participating in the development only needs to implement their own class, and has nothing to do with others!

    

Let's take a look again, why does Inversion of Control (IOC) have such a name? Let's compare:

    

Before the software system introduced the IOC container, as shown in Figure 1, object A depends on object B. When object A is initialized or runs to a certain point, it must actively create object B or use the created object B. Whether you create or use object B, you have control over it.

    

After the software system introduced the IOC container, this situation has completely changed. As shown in Figure 3, due to the addition of the IOC container, the direct connection between object A and object B is lost. Therefore, when object A runs to object B At the time, the IOC container will actively create an object B and inject it where the object A needs it.

    

Through the comparison before and after, it is not difficult to see: the process of object A obtaining dependent object B has changed from active behavior to passive behavior, and the right of control is reversed. This is the origin of the name "inversion of control".

 

73. 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, messages and test modules as shown in the figure below.

 

 

 


74. What are the common injection methods for spring?

 

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

 

  1. Constructor injection

  2. setter injection

  3. Annotation-based injection

 

75. 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 does not have thread-safe features, but the specific scope of the Bean should be studied.

 

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

  • request: For each HTTP request, a Bean defined by 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 scope is valid only when Spring is used in web applications

  • 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 scope is valid only when Spring is used in web applications

 

Among the more commonly used scopes are singleton and prototype. For a singleton-scoped bean, 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 with that id, Spring will create a new Bean instance and 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 the bean instance of the singleton scope is created successfully, it can be reused. Therefore, unless necessary, try to avoid setting the Bean to prototype scope.

 

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

 

The Spring container is responsible for creating beans in the application while 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.

 

78. What are the implementation methods of spring transaction?

 

  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

 

79. Tell me about Spring's transaction isolation?

 

The transaction isolation level refers to the degree of isolation between a transaction's modification of data 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 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.

 

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

 

Spring MVC operation flow chart:

 

 

Spring 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;

      

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

      

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

       

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's parameters, Spring will help you do some extra work according to your configuration:

 

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

  • Data conversion: Data conversion of the request message. Such as String converted to Integer, Double, etc.

  • Data root formatting: Data formatting of request messages. Such as converting a string into a formatted number or formatted date, etc.

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

      

5. After the Handler is executed, it returns a ModelAndView object to DispatcherServlet;

      

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

      

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

      

8. Return the rendering result to the client.

 

81. What are the components of spring mvc?

 

The core components of Spring MVC:

 

  1. DispatcherServlet: The central controller, which forwards the request to a specific control class

  2. Controller: The controller that specifically processes the request

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

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

  5. ViewResolver: View resolver, resolve specific views

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

 

82. 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, 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: Specifies that certain parameter values ​​must be included in the request before the method is processed.

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

At last

The content of the interview questions is over here, I hope it will be helpful to everyone.

Finally, I want to say something to you. I have worked for so many years and have interviewed some people for others. Whether it is from the perspective of the interviewer or the leader, in addition to interview skills and experience, great technology and project experience are also their trump cards and confidence. Core technology sharing of first-tier manufacturers

 It took me a long time to sort out some learning materials. What I posted above is the tip of the iceberg in the materials. I hope I can help you! Click to learn together cipher: csdn

                         

  I will share more pure dry goods articles in the follow-up, and hope to really help you. Your support is my biggest motivation!

Guess you like

Origin blog.csdn.net/weixin_50333534/article/details/108834772