Java Interview - Spring (Part 1)

1. What is spring?

Spring is an open source framework for java enterprise applications.
Spring is mainly used to develop Java applications, but some extensions are aimed at building web applications for the J2EE platform.
The goal of the Spring Framework is to simplify Java enterprise application development and promote good programming habits through a POJO-based programming model.

2. Why do you use the Spring framework in your project?

If you ask this question, just talk about the benefits of the Spring framework. For example, Spring has the following characteristics:

  • Lightweight : Spring is lightweight, the basic version is about 2MB.
  • Inversion of Control : Spring achieves loose coupling through inversion of control, objects give their dependencies instead of creating or finding dependent objects.
  • Aspect-Oriented Programming (AOP) : Spring supports aspect-oriented programming and separates application business logic from system services. Container: Spring contains and manages the lifecycle and configuration of objects in the application.
  • MVC framework : Spring's WEB framework is a well-designed framework and a good substitute for the Web framework.
  • Transaction management : Spring provides a persistent transaction management interface that can be extended from local transactions down to global transactions (JTA).
  • Exception handling : Spring provides a convenient API to convert specific technology-related exceptions (such as those thrown by JDBC, Hibernate or JDO) into consistent unchecked exceptions.

3. What is the difference between Autowired and Resource keywords?

Detailed analysis

Both @Resource and @Autowired are used for bean injection. In fact, @Resource is not a Spring annotation. Its package is javax.annotation.Resource, which needs to be imported, but Spring supports the injection of this annotation.
1. Common points
Both can be written on fields and setter methods. If both are written on the field, then there is no need to write the setter method.
2. Differences
(1) @Autowired
@Autowired provides annotations for Spring, you need to import the package
org.springframework.beans.factory.annotation.Autowired; only inject byType.

public class TestServiceImpl {
    
    
	 // 下面两种@Autowired只要使用一种即可
	 @Autowired
	 private UserDao userDao; // 用于字段上
	 
	 @Autowired
	 public void setUserDao(UserDao userDao) {
    
     // 用于属性的方法上
	 	this.userDao = userDao;
	 }
}

The @Autowired annotation assembles dependent objects according to type (byType). By default, it requires that dependent objects must exist. If null values ​​are allowed, you can set its required attribute to false. If we want to assemble by name, we can use it in conjunction with the @Qualifier annotation. as follows:

public class TestServiceImpl {
    
    
	@Autowired
	@Qualifier("userDao")
	private UserDao userDao; 
}

(2)@Resource

@Resource is automatically injected by ByName by default, provided by J2EE, and the package javax.annotation.Resource needs to be imported.
@Resource has two important attributes: name and type, and Spring resolves the name attribute of the @Resource annotation to the name of the bean, and the type attribute resolves to the type of the bean. Therefore, if the name attribute is used, the byName automatic injection strategy is used, and when the type attribute is used, the byType automatic injection strategy is used. If neither the name nor the type attribute is specified, the byName automatic injection strategy will be used through the reflection mechanism.

public class TestServiceImpl {
    
    
	// 下面两种@Resource只要使用一种即可
	@Resource(name="userDao")
	private UserDao userDao; // 用于字段上
	
	@Resource(name="userDao")
	public void setUserDao(UserDao userDao) {
    
     // 用于属性的setter方法上
		this.userDao = userDao;
	}
}

Note: It is best to put @Resource on the setter method, because this is more in line with the object-oriented thinking, and the properties are manipulated through set and get instead of directly.

@Resource assembly order:

  • ① If both name and type are specified, the only matching bean is found from the Spring context for assembly, and an exception is thrown if it cannot be found.
  • ② If the name is specified, the bean with the matching name (id) will be searched from the context for assembly, and an exception will be thrown if it cannot be found.
  • ③If type is specified, find the only bean that matches similarly from the context for assembly, if it cannot find or find more than one, an exception will be thrown.
  • ④If neither name nor type is specified, it will be automatically assembled according to the byName method; if there is no match, it will fall back to an original type for matching, and if it matches, it will be automatically assembled.

The role of @Resource is equivalent to @Autowired, except that @Autowired is automatically injected according to byType.

4. There are several ways of dependency injection, and what are they?

1. Constructor injection The dependent object is injected into the dependent object through the parameters of the constructor, and injected when the object is initialized.

Advantages: A usable object is available after object initialization is complete.

Disadvantages: When there are many objects to be injected, the constructor parameter list will be very long; not flexible enough. If there are multiple injection methods, and each method only needs to inject a few specified dependencies, then it is necessary to provide multiple overloaded constructors, which is troublesome.

2. Setter method injection The IoC Service Provider injects the dependent object into the dependent class by calling the setter function provided by the member variable.

Pros: Flexible. Objects that are needed can be selectively injected.

Disadvantages: After the dependent object is initialized, it cannot be used because the dependent object has not been injected yet.

3. Interface injection The dependent class must implement the specified interface, and then implement a function in the interface, which is used for dependency injection. The parameter of this function is the object to be injected.

Advantages: In interface injection, the name of the interface and the name of the function are not important, as long as the parameter of the function is the type of the object to be injected.

Cons: The intrusive line is too strong and not recommended.

PS: What is an intrusive row? If class A wants to use a function provided by others, if in order to use this function, it needs to add additional code to its own class, which is intrusive.

5. Tell me what is Spring

Spring is a lightweight IoC and AOP container framework. It is a set of frameworks that provide basic services for Java applications. The purpose is to simplify the development of enterprise applications. It allows developers to only care about business needs. There are three common configuration methods: XML-based configuration, annotation-based configuration, and Java-based configuration.

It mainly consists of the following modules:
Spring Core : core class library, providing IOC services;
Spring Context : providing framework-style Bean access methods, and enterprise-level functions (JNDI, scheduled tasks, etc.);
Spring AOP : AOP services;
Spring DAO : The abstraction of JDBC simplifies the handling of data access exceptions;
Spring ORM : Support for existing ORM frameworks;
Spring Web : Provides basic Web-oriented comprehensive features, such as multi-party file uploads;
Spring MVC : Provides Web-oriented Application's Model-View-Controller implementation.

6. Talk about your understanding of Spring MVC

What is MVC mode
MVC: MVC is a design pattern
MVC schematic diagram:
insert image description here
analysis:
M-Model model (complete business logic: composed of javaBean, service+dao+entity)

V-View view (for interface display jsp, html...)

C-Controller controller (receive request—>call model—>dispatch page according to result)

springMVC is an MVC open source framework, springMVC=struts2+spring, springMVC is equivalent to the integration of Struts2 plus sring, but there is a doubt here, what is the relationship between springMVC and spring? There is a good explanation for this on Baidu Encyclopedia: It means that springMVC is a follow-up product of spring. In fact, spring provides an MVC module for web applications on the basis of the original. SpringMVC can be simply understood as spring A module (like AOP, IOC modules), it is often said on the Internet that springMVC and spring are seamlessly integrated. In fact, springMVC is a sub-module of spring, so there is no need to integrate with spring at all.

Working principle:
insert image description here
1. The user sends a request to the front controller DispatcherServlet.

2. DispatcherServlet receives a request to call HandlerMapping processor mapper.

3. The processor mapper finds the specific processor (can be searched according to the xml configuration and annotation), generates the processor object and the processor interceptor (if there is one), and returns it to the DispatcherServlet.

4. DispatcherServlet calls HandlerAdapter processor adapter.

5. The HandlerAdapter calls a specific processor (Controller, also called a back-end controller) after adaptation.

6. After the execution of the Controller is completed, it returns to the ModelAndView.

7. HandlerAdapter returns the controller execution result ModelAndView to DispatcherServlet.

8. DispatcherServlet passes ModelAndView to ViewReslover view resolver.

9. ViewReslover returns a specific View after parsing.

10. DispatcherServlet renders the view according to the View (that is, fills the model data into the view).

11. DispatcherServlet responds to the user.

Component Description:

The following components typically provide implementations using the framework:

DispatcherServlet : As a front-end controller, the center of the entire process control, control the execution of other components, unified scheduling, reduce the coupling between components, and improve the scalability of each component.

HandlerMapping : Implement different mapping methods by extending the processor mapper, such as: configuration file method, interface implementation method, annotation method, etc.

HandlAdapter : Support more types of processors by extending the processor adapter.

ViewResolver : By extending the view resolver, it supports more types of view resolution, such as: jsp, freemarker, pdf, excel, etc.

Components: 1. Front-end controller DispatcherServlet (no need for engineers to develop), provided by the framework Function: receive requests, respond to results, equivalent to forwarders, central processing units. With dispatcherServlet, the coupling between other components is reduced. When the user request arrives at the front controller, it is equivalent to c in the MVC mode. The dispatcherServlet is the center of the entire process control. It calls other components to process the user's request. The existence of the dispatcherServlet reduces the coupling between components.
2. Processor mapper HandlerMapping (no need for engineer development), provided by the framework : find Handler according to the requested url HandlerMapping is responsible for finding Handler or processor according to user request, springmvc provides different mappers to achieve different mapping methods, for example : Configuration file method, interface implementation method, annotation method, etc.
3. The role of the processor adapter HandlerAdapter: to execute the Handler according to specific rules (the rules required by the HandlerAdapter) to execute the processor through the HandlerAdapter. This is the application of the adapter mode, and more types of processors can be executed by extending the adapter.
4. Processor Handler (requires engineer development) Note: When writing Handler, follow the requirements of HandlerAdapter,
so that the adapter can execute Handler correctly
. Handler is the back-end controller following the DispatcherServlet front-end controller. Specific user requests are processed. Since Handlers are related to specific user business requests, engineers are generally required to develop Handlers according to business requirements.
5. View resolver View resolver (no need for engineer development), provided by the frameworkFunction: Perform view analysis, and resolve it into a real view (view) according to the logical view name. View Resolver is responsible for generating a View view from the processing result. View Resolver first resolves the logical view name into a physical view name, that is, a specific page address, and then generates a View view Object, and finally render the View and display the processing results to the user through the page. The springmvc framework provides many View view types, including: jstlView, freemarkerView, pdfView, etc. In general, it is necessary to display model data to users through page tags or page template technology, and engineers need to develop specific pages according to business needs.
6. View View (requires engineers to develop jsp...) View is an interface, and the implementation class supports different View types (jsp, freemarker, pdf...)

The specific process steps of the core architecture are as follows:
1. First, the user sends a request --> DispatcherServlet. After receiving the request, the front-end controller does not process it by itself, but entrusts it to other parsers for processing, as a unified access point, for global process control;

2. DispatcherServlet——>HandlerMapping, HandlerMapping will map the request to a HandlerExecutionChain object (including a Handler processor (page controller) object, multiple HandlerInterceptor interceptors) objects, through this strategy mode, it is easy to add new mappings Strategy;

3. DispatcherServlet——>HandlerAdapter, HandlerAdapter will package the processor as an adapter to support multiple types of processors, that is, the application of the adapter design pattern, so that it is easy to support many types of processors;

4. HandlerAdapter——>Invoke the function processing method of the processor, HandlerAdapter will call the function processing method of the real processor according to the adaptation result, complete the function processing; and return a ModelAndView object (including model data, logical view name) ;

5. The logical view name of ModelAndView --> ViewResolver, ViewResolver will resolve the logical view name into a specific View. Through this strategy mode, it is easy to replace other view technologies;

6. View --> Rendering, View will render according to the incoming Model model data, the Model here is actually a Map data structure, so it is easy to support other view technologies;

7. Return control to DispatcherServlet, and DispatcherServlet returns a response to the user, and this process ends.

Seeing these steps, I believe that everyone feels very confused, which is normal, but here is mainly to let everyone understand several components in springMVC:

Front-end controller (DispatcherServlet) : Receive requests and respond to results, which is equivalent to the CPU of a computer.
Processor Mapper (HandlerMapping) : Find the processor according to the URL.
Processor (Handler) : Programmers are required to write code to process logic.
Processor Adapter (HandlerAdapter) : The processor will be packaged into an adapter, so that it can support multiple types of processors, analogous to notebook adapters (adapter mode applications).
View Resovler (ViewResovler) : Perform view resolution, process the returned strings, and parse them into corresponding pages.

7. What are the common annotations of SpringMVC?

@RequestMapping : An annotation for processing request url mapping, which can be used on classes or methods. When used on a class, it means that all methods in the class that respond to requests use this address as the parent path.

@RequestBody : The annotation realizes receiving the json data of the http request and converting the json into a java object.

@ResponseBody : The annotation implementation converts the object returned by the conreoller method into a json object to respond to the client.

8. Talk about your understanding of Spring's AOP

AOP (Aspect-Oriented Programming, Aspect-Oriented Programming) can encapsulate the logic or responsibility (such as transaction processing, log management, permission control, etc.) , reduce the coupling between modules, and facilitate future scalability and maintainability.

Spring AOP is based on dynamic proxy. If the object to be proxied implements an interface, Spring AOP will use JDK dynamic proxy to create the proxy object; for objects that do not implement the interface, JDK dynamic proxy cannot be used, and instead Use CGlib dynamic proxy to generate a subclass of the proxy object as a proxy.
insert image description here
Note: implements and extends in the figure. That is, one is the interface and the other is the implementation class.

Of course, AspectJ can also be used. AspectJ has been integrated in Spring AOP. AspectJ should be regarded as the most complete AOP framework in the Java ecosystem. After using AOP, we can abstract some common functions and use them directly where they are needed, which can greatly simplify the amount of code. We need to add new functions conveniently and improve the scalability of the system. AOP is used in scenarios such as log function, transaction management, and authority management.

As long as you mention AspectJ here, the interviewer is likely to continue to ask:

9. What is the difference between Spring AOP and AspectJ AOP?

Spring AOP is a runtime enhancement, while AspectJ is a compile-time enhancement. Spring AOP is based on proxying (Proxying), while AspectJ is based on bytecode manipulation (Bytecode Manipulation).

Spring AOP has integrated AspectJ, and AspectJ should be regarded as the most complete AOP framework in the Java ecosystem. AspectJ is more powerful than Spring AOP, but Spring AOP is relatively simpler.

If we have fewer aspects, then the performance difference between the two is not big. However, when there are too many aspects, it is best to choose AspectJ, which is much faster than SpringAOP.

May continue to ask:

In Spring AOP, what is the difference between concerns and crosscutting concerns?

A concern is the behavior of a module in an application, and a concern may be defined as a function we want to achieve. A cross-cutting concern is a concern that is used throughout the application and affects the entire application, such as logging, security, and data transfer, functions that are required by almost every module of the application. So these are crosscutting concerns.

So what is a join point? A join point represents a location in an application where we can insert an AOP aspect, which is actually a location where the application executes Spring AOP.

What is the entry point? A pointcut is a join point or set of join points at which advice is to be executed. Pointcuts can be specified by expressions or matches.

What is a notification? What types are there?

Notification is an action to be done before or after the execution of the method. In fact, it is a code segment to be triggered by the Spring AOP framework when the program is executed.

Spring aspects can apply five types of advice:

  • before: Pre-advice, which is called before a method is executed.
  • after: Advice invoked after the method execution, regardless of whether the method execution was successful or not.
  • after-returning: Advice to be executed only after the method completes successfully.
  • after-throwing: Advice executed when the method exits with an exception thrown.
  • around: Advice called before and after method execution.

10. Tell me about your understanding of Spring's IOC?

(1) IOC is the inversion of control, which refers to the transfer of control over the creation of objects. In the past, the initiative and timing of creating objects were controlled by oneself, but now this power is transferred to the Spring container, and the container creates instances and manages the dependencies between instances according to the configuration files. Loose coupling between objects is also conducive to the reuse of functions. DI dependency injection and inversion of control are descriptions from different angles of the same concept, that is, the application relies on the IoC container to dynamically inject the external resources required by the object at runtime.

(2) The most intuitive expression is that IOC allows the creation of objects without going to new, which can be automatically produced by spring, using the reflection mechanism of java, dynamically creating objects and managing objects at runtime according to the configuration file, and calling the object's method.

(3) Spring's IOC has three injection methods: constructor injection, setter method injection, and injection based on annotations.

IoC keeps collaborating components loosely coupled, while AOP programming allows you to separate the functions throughout the application layers to form reusable functional components.

Guess you like

Origin blog.csdn.net/weixin_39763930/article/details/117319914