An article to help you solve Spring interview questions

Table of contents

1. SpringAOC

2. SpringIOC

3. SpringMVC

4. Common annotations for Spring and SpringMVC


1. SpringAOP

1. What is AOP
AOP (Aspect Oriented Programming) is an aspect-oriented programming idea. Aspect-oriented programming abstracts the program into various aspects, that is, dissects the inside of the object, extracts the common behaviors that affect multiple classes into a reusable module, reduces the repetitive code of the system, reduces the coupling between modules, and enhances the code operability and maintainability .

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 part that has little relationship with it is the cross-cutting concern. One characteristic of cross-cutting concerns is that they often occur in multiple places in the core concern, but are basically similar everywhere. Such as authority authentication, logging, transaction processing, and enhanced processing.

> Benefits brought by AOP: Let us "concentrate on doing things"

2. Spring AOP proxy mechanism
Spring will generate a dynamic proxy object for the target object during runtime, and implement enhancements to the target object in the proxy object. The bottom layer of Spring AOP performs horizontal weaving for the target object (Target Bean) through the following two dynamic proxy mechanisms.

- **JDK dynamic proxy: **Spring AOP's default dynamic proxy method. If the target object implements several interfaces, Spring uses the JDK's java.lang.reflect.Proxy class for proxy.
- **CGLIB dynamic proxy:** If the target object does not implement any interface, Spring uses the CGLIB library to generate a subclass of the target object to implement the proxy for the target object.

> Note: Since methods marked as final cannot be overridden, such methods cannot be proxied either through the JDK dynamic proxy mechanism or the CGLIB dynamic proxy mechanism.


3. Core concept
- Joinpoint**: refers to those points that are intercepted (clear points during program execution, such as method calls, or exceptions thrown). In Spring, they can be intercepted by dynamic agents. The method of the target class.
- **Pointcut**: A collection of multiple connection points that defines which connection points the notification should apply to.
- **Advice**: refers to what to do after intercepting the Joinpoint, that is, the content that enhances the entry point.
- **Target**: refers to the target object of the agent.
- **Weaving (implantation)**: refers to the process of applying enhancement code to the target and generating a proxy object.
- **Proxy**: refers to the generated proxy object (the object created after applying the notification to the target object).
- **Aspect**: The combination of entry points and notifications.

4.Notification classification:

1) The pre-notification org.springframework.aop.MethodBeforeAdvice implements enhancement before the target method is executed.
2) Post notification org.springframework.aop.AfterAdvice implements enhancement after the target method is executed.
3) The post-return notification org.springframework.aop.AfterReturningAdvice implements enhancements after the target method is executed and a return value is returned.
4) Surround notification org.aopalliance.intercept.MethodInterceptor implements enhancements before and after the target method is executed.
5) Exception notification org.springframework.aop.ThrowsAdvice implements enhancements after the method throws an exception.
6) Introduce notification org.springframework.aop.IntroductnInterceptor to add some new methods and properties to the target class.

2. SpringIOC

1. What is Spring?
The Spring Framework is a one-stop lightweight solution for layered, aspect-oriented Java applications. It is the core and foundation of the Spring technology stack and is designed to solve the complexity of enterprise-level application development. Created.

> Simply put, Spring is a lightweight Inversion of Control (IoC) and Aspect-Oriented (AOP) container framework. The middle layer framework between SpringMVC and Mybatis, its function: connecting the upper and lower parts, equivalent to the adhesive

2. Core concepts:
1) IOC: The abbreviation of Inverse of Control, translated as "Inversion of Control", refers to handing over the object creation process to Spring for management.

2) AOP: The abbreviation of Aspect Oriented Programming, translated as "aspect-oriented programming". AOP is used to encapsulate the public behaviors of multiple classes and encapsulate the logic that has nothing to do with the business but is commonly called by the business modules, reducing the duplication of code in the system and reducing the coupling between modules. In addition, AOP also solves some system-level problems, such as logs, transactions, permissions, etc.

3. Core architecture
1) **Spring Core**: Provides dependency injection and Bean management functions. The main component is `BeanFactory`, which uses the inversion of control pattern to separate application configuration and dependency specifications from the actual application code;

2) **Spring Context**: Expands the concept of `BeanFactory`, adds support for internationalization, event propagation, and verification, etc. In addition, it also provides many enterprise services and support for template framework integration;

3) **Spring Web**: Built on the Context module, it provides a context suitable for Web applications. In addition, this module also provides some service-oriented support and integration of Spring and other web frameworks;

4) **Spring Web MVC**: It is a full-featured MVC implementation for building Web applications, which accommodates a large number of view technologies, such as JSP, Velocity, POI, etc.;

5) **Spring AOP**: Provides support for aspect-oriented programming for objects managed by the Spring container;

6) **Spring DAO**: This layer encapsulates access to the database and handles error messages thrown by it. It also provides transaction management based on the AOP module;

7) **Spring ORM** (Object Relational Mapping): Spring supports multiple ORM frameworks (Mybatis, Hibernate), simplifying database operations.

4. What is Inversion of Control (IOC)?
In traditional Java applications, if a class wants to call a property or method in another class, it usually first adds the latter object to its code through new Object(). Create it before you can call the property or method. For ease of understanding and description, we can call the former the "caller" and the latter the "callee". In other words, the caller has control over the creation of the callee object.
The biggest change brought about by IoC is not at the code level, but at the ideological level, a change in master-slave transposition. Originally the caller was the active party, and would take the initiative and create whatever resources it wanted to use. However, in Spring applications, the IoC container holds the initiative, and the caller became the passive party, passively waiting for the IoC container. Create the objects (Beans) it requires.
This process has an inversion of control at the responsibility level, reversing the creation of objects originally implemented by the caller through code to the IoC container to help implement it, so we call this process Spring's "inversion of control".

5. Dependency Injection (DI)
In object-oriented, there is a relationship called "dependency" between objects. Simply put, a dependency relationship means that one object needs to use another object, that is, there is an attribute in the object, and the attribute is an object of another class.
The core idea of ​​inversion of control is that Spring is responsible for the creation of objects. During the object creation process, Spring will automatically inject the objects it depends on into the current object based on the dependency relationships. This is the so-called "dependency injection".

> That is, the Spring IOC container dynamically injects certain dependencies into the components

3. SpringMVC

1. What is Spring MVC?
Spring MVC is a lightweight web framework based on Java that implements the request-driven type of MVC design pattern. By separating Model, View, and Controller, it decouples the responsibilities of the web layer and decouples complex web applications. Divide it into logically clear parts to simplify development, reduce errors, and facilitate cooperation among developers within the team.

2. Working principle
1. When the user sends a request, the first thing that enters is the front-end controller DispatcherServlet
2. The front-end controller (DispacherServlet) sends the request from the user to the processor mapper (HandlerMapping)
3. The processor mapper is based on The user's request sent by the front-end controller finds the corresponding controller (Handler), encapsulates it into a processor execution chain, and returns it to the front-end controller.
4. After the processor adapter receives the execution chain from the front-end controller, it finds the specific controller (that is, its corresponding method or logic) that is called by the processor adapter (HandlerAdapter) that executes this execution chain. 5.
Processor The adapter (HandlerAdaptoer) will call the corresponding specific Controller (processing business logic)
6. After the controller is executed, a ModelAndView object will be returned to the processor adapter
7. The processor adapter will return the returned ModelAndView object to the front-end controller ( All business processing will be completed here, and the next step is to respond to the user in the form of a page)
8. The front-end controller hands the returned ModelAndView object to the view resolver (ViewResolver), and the view resolver passes it according to the The View object is parsed into the corresponding page object
9. ViewResolver returns the encapsulated page object and Model object to DIspatcherServlet
10. The front-end controller then hands the returned Model object to the view (View)
11. The view passes the Model The object renders the page again (populating the model data into the view) and then returns it to the front controller.
12. The front-end controller responds to the browser with the completed result, and then the browser displays it to the user.


3. Core components
1) DispatcherServlet is the front-end controller in the SpringMVC framework.
Function: Unified processing of requests and responses from users, equivalent to an intermediate converter, reducing scheduling between various components and reducing coupling.

2) HandlerMapping is the function of the processor mapper in the SpringMVC framework
: find the corresponding Handler according to the url and method sent by the request (that is, there will be many methods and logic in a project using the SpringMVC framework. The function of this component is Find the corresponding methods and components and return them to the front-end controller)

3) Handler processor, please note that this needs to be developed by engineers themselves.
Function: Under the control of DispatcherServlet, Handler processes specific user requests. 

4) HandlerAdapter is a processor adapter provided by the SpringMVC framework
. Its function is to execute the relevant processor Handler according to specific rules based on the processor Handler information found by the mapper.

5) ViewResolver is the view resolver provided by the SpringMVC framework.
Function: Just as its name suggests, it is used to parse the processing results into views to display to the user. The view parser parses the logical view name into a physical view name, generates a View object, and finally renders the view and responds to the user.

6) View is a view provided by the developer itself
. Its function is to render the page according to the requirements of the model object, and then the front-end controller responds to the user.

4. Common annotations for Spring and SpringMVC

1. Spring common annotations:
1) @Repository declares the DAO class as a Bean
2) @Service is used to modify the components of the service layer
3) @Controller usually acts on the control layer and will be used in Spring MVC
4) @Component is a generic The concept of transformation only represents a component (Bean) in spring and can be used at any level.
5) @Scope is a scope in the spring IoC container. It has the following scopes in the Spring IoC container: singleton (single case) , prototype (multiple examples), Web scope (reqeust, session, globalsession), custom scope.
6) @Autowired will automatically match the bean in the Spring context (the default is type matching), and automatically inject it into the corresponding place.
7) @Resource:
(1) There is no content behind @Resource. By default, the name attribute is used to match the bean. If it cannot be found, press type to match
(2) If name or type is specified, the bean will be matched according to the specified type.
(3) If name and type are specified, the bean will be matched according to the specified name and type. If any mismatch occurs, an error will be reported. @Transactional annotation used in declarative transaction management programming

2. SpringMVC common annotations:
1) @RequestMapping: The annotation is an annotation used to process request address mapping. It can be used to map a request or a method and can be used on a class or method.
(1) When used on a method, it means that adding the address in the annotation on the method under the parent path of the class will access the method. (
2) When used on a class, it means that all methods in the class that respond to requests will use this address. as parent path.

2) @RequestParam: Mainly used to map the data in the request parameter area to the parameters of the control layer method

3) @ModelAttribute:
(1) Bind request parameters to the command object: When placed on the input parameter of the function processing method, it is used to bind multiple request parameters to a command object, thereby simplifying the binding process and automatically exposing it as Model data is used for view page display;
(2) Exposing the form reference object as model data: When placed on the general method (non-functional processing method) of the processor, it prepares the form reference object to be displayed for the form, such as registration The city that needs to be selected, etc., and before executing the function processing method (@RequestMapping annotated method), it is automatically added to the model object for use when displaying the view page; (3) Expose the @RequestMapping method return value as model
data : When placed on the return value of the function processing method, it exposes the return value of the function processing method as model data, which is used for view page display.

4) @SessionAttributes: By default, when the attribute scope in ModelMap is the request level, that is to say, when this request ends, the attributes in ModelMap will be destroyed. If you want to share the attributes in the ModelMap among multiple requests, you must dump its attributes into the session so that the attributes of the ModelMap can be accessed across requests; spring allows us to selectively
specify which attributes in the ModelMap need to be dumped to session, so that these attributes can be accessed in the attribute list of the corresponding ModelMap in the next request.
SpringMVC provides us with such an annotation to implement the above scenario: `@SessionAttributes`: Share the attribute values ​​​​of ModelMap into the session.

5) @RequestBody: Mainly used to receive data in the json string passed from the front end to the back end (that is, the data in the request body); GET
method does not have a request body, so when using @RequestBody to receive data, ** the front end cannot be used Submit data using GET method instead of submitting data using POST method**. In the same receiving method on the backend, @RequestBody and @RequestParam() can be used at the same time. There can be at most one @RequestBody, but there can be multiple @RequestParam().
In short:
(1) One request: there is only one @RequestBody;
(2) One request: there can be multiple @RequestParam.

6) @RequestHeader: Use the @RequestHeader annotation to obtain the specified request header information. If you want to obtain all request header information, you can use any of the three Maps: Map<String,String>, MultiValueMap<String,String>, and HttpHeaders to encapsulate the name and value of all request headers.

7) @PathVariable: This annotation requests the binding of the template variable part in the URI to the method parameter of the processor function processing method.
That is, when using the @RequestMapping URI template style mapping, that is, someUrl/{paramId}, the paramId at this time can bind the value passed by it to the parameter of the method through the @Pathvariable annotation. Count on.

8) @CookieValue: The annotation mainly maps the requested Cookie data to the parameters of the function processing method.

The final suggestion is:

Being well prepared, answering clearly and concisely, going deep into the rationale, providing examples and experiences, and demonstrating humility and honesty are some useful guidelines when answering Spring interview questions. Remember, before answering a question, listen carefully to the question and make sure you understand it before giving your answer.

Guess you like

Origin blog.csdn.net/m0_73647713/article/details/132813287