That year, this big Spring family made me stand out in the interview

Foreword:

The Spring framework is like a family, with many derivative products such as boot, security, jpa, etc. But their foundation is Spring's ioc and aop. ioc provides a container for dependency injection, and aop solves cross-section-oriented programming; and then implements the advanced functions of other extended products on the basis of the two. Let’s talk carefully about the story of Spring’s big family today.
Insert picture description here

Insert picture description here

1. Why use spring?

Spring provides ioc technology, and the container will help you manage dependent objects, so you don't need to create and manage dependent objects yourself, which makes it easier to decouple the program.
Spring provides transaction support, making transaction operations more convenient.
Spring provides slice-oriented programming, which can handle certain types of problems more conveniently.
More convenient framework integration, spring can easily integrate other frameworks, such as MyBatis, hibernate, etc.

2. Explain what is aop?

Aop is a technology for aspect-oriented programming that achieves unified maintenance of program functions through pre-compilation and runtime dynamic agents.
Simply put, it is the programming idea of ​​uniformly processing a certain "aspect" (class) of problems, such as uniform processing of logs and exceptions.

In addition, I have collected more than 20 years of company interview knowledge points, as well as various Java core knowledge points for free to share with you. I think it is very useful for interviews. If you want information, please click 795983544 secret code CSDN.

Insert picture description here

3. Explain what is ioc?

ioc: Inversion of Control (Chinese: Inversion of Control) is the core of spring. For the spring framework, spring is responsible for controlling the life cycle of objects and the relationship between objects.
In simple terms, control refers to the current object's control over internal members; inversion of control refers to that this kind of control is not managed by the current object, but managed by other (classes, third-party containers).

4. What are the main modules of spring?

spring core: the most basic part of the framework, providing ioc and dependency injection features.
spring context: a context package built on the basis of the core package, providing a framework-style object access method.
spring dao: Data Access Object provides an abstraction layer for JDBC.
spring aop: Provides an aspect-oriented programming implementation, allowing you to customize interceptors, pointcuts, etc.
Spring Web: Provides integrated features for Web development, such as file upload, ioc container initialization using servlet listeners, and ApplicationContext for Web.
spring Web mvc: The mvc package in spring provides an implementation of Model-View-Controller (MVC) for Web applications.

5. What are the common injection methods for spring?

setter attribute injection
constructor injection
annotation method injection

6. Are beans in spring thread safe?

The bean in spring is in singleton mode by default, and the spring framework does not encapsulate singleton beans in multiple threads.
In fact, most of the time spring beans are stateless (such as the dao class), and all beans are safe to some extent, but if the bean is stateful (such as the view model object), it is up to the developer to ensure thread safety. The simplest thing is to change the scope of the bean and change "singleton" to "prototype", so that the request bean is equivalent to new Bean(), so thread safety can be guaranteed.
State is to have data storage function.
Stateless means not saving data.

7. What scope of beans does spring support?

Spring supports 5 scopes, as follows:
singleton: there is only one bean instance in the spring ioc container, and the bean exists in singleton mode, which is the default value of the system;
prototype: each time a bean is called from the container, a new example is created, both Each getBean() is equivalent to the execution of the new Bean() operation;
the scope of the Web environment:
request: each http request will create a bean;
session: the same http session shares a bean instance;
global-session: for portlet Container, because each portlet has a separate session, globalsession provides a global http session.
Note: The use of prototype scope requires careful thinking, because frequent creation and destruction of beans will bring a lot of performance overhead.

8. What are the ways for spring to automatically assemble beans?

no: The default value, which means that there is no automatic assembly, and explicit bean references should be used for assembly.
byName: It injects object dependencies based on the name of the bean.
byType: It injects object dependencies based on type.
Constructor: Injecting dependencies through the constructor requires a large number of parameters.
autodetect: The container is first assembled by autowire through the constructor, if not, it is automatically assembled through byType.

9. What are the implementation methods of spring transaction?

Declarative transactions: There are also two ways to implement declarative transactions, based on the xml configuration file and the annotation method (add @Transaction annotation to the class).
Coding method: Provides management and maintenance affairs in the form of coding.

10. Tell me about Spring's transaction isolation?

Insert picture description here

Spring has five isolation levels, the default value is ISOLATION_DEFAULT (using database settings), the other four isolation levels are consistent with the database isolation level:
ISOLATION_DEFAULT: I set the isolation level with the underlying database, and I will use whatever the database is set;
ISOLATIONREADUNCOMMITTED : Uncommitted read, the lowest isolation level, before the transaction is committed, it can be read by other transactions (phantom reads, dirty reads, and non-repeatable reads will occur);
ISOLATIONREADCOMMITTED: commit read, a transaction can only be read by other transactions after it is committed To (will cause phantom reads, non-repeatable reads), the default level of SQL server;
ISOLATIONREPEATABLEREAD: Repeatable reads, to ensure that when the same data is read multiple times, its value is consistent with the content at the beginning of the transaction. Reading is prohibited Uncommitted data of other transactions (will cause phantom reads), MySQL's default level;
ISOLATION_SERIALIZABLE: serialization, the most costly and most reliable isolation level, this isolation level can prevent dirty reads, non-repeatable reads, and phantom reads.
Dirty read: indicates that a transaction can read data that has not yet been committed in another transaction. For example, a transaction tries to insert record A, and the transaction has not yet committed, and then another transaction tries to read record A.
Non-repeatable reading: refers to reading the same data multiple times within a transaction.
Phantom reading: Refers to the different result sets returned by multiple queries within the same transaction. For example, the same transaction A has n records in the first query, but there are n+1 records in the second query under the same conditions, which seems to be an illusion. The reason for the phantom read is that another transaction adds, deletes, or modifies the data in the first transaction result set. If the data content of the same record is modified, the records of all data rows become more or less.

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

spring mvc sends the request to DispatcherServlet first.
DispatcherServlet queries one or more HandlerMappings to find the Controller that processes the request.
DispatcherServlet then submits the request to the corresponding Controller.
After the Controller processes the business logic, it returns a ModelAndView.
Dispathcher queries one or more ViewResolver view resolvers to find the view object specified by the ModelAndView object.
The view object is responsible for rendering back to the client.

12. What are the components of spring mvc?

The front controller DispatcherServlet.
Mapping controller HandlerMapping.
Processor Controller.
Model and view ModelAndView.
View resolver ViewResolver.

13. What is the role of @RequestMapping?

Map the http request to the corresponding class/method.

14. What is the role of @Autowired?

@Autowired It can annotate class member variables, methods and constructors, complete the work of automatic assembly, and eliminate set/get methods through the use of @Autowired.
Spring Boot/Spring Cloud

15. What is spring boot?

Spring boot serves spring and is used to simplify the initial setup and development of new spring applications.

16. Why use spring boot?

Simple configuration,
stand-alone operation,
automatic assembly,
no code generation and xml configuration
, application monitoring,
easy to use,
improve development efficiency

17. What is the core configuration file of spring boot?

Two configuration files at the core of spring boot:
bootstrap (. yml or. properties): boostrap is loaded by the parent ApplicationContext, which is loaded first than applicato, and the properties in boostrap cannot be overwritten;
application (. yml or. properties): used for Automatic configuration of spring boot project.

18. What types of spring boot configuration files are there? What is the difference between them?

The configuration file has .properties format and .yml format. The main difference between them is the calligraphy style.
The properties configuration is as follows:
spring. RabbitMQ. port=5672
. The yml configuration is as follows:
spring:
RabbitMQ:
port: 5672. The
yml format does not support @PropertySource annotation import.

19. What are the ways to achieve hot deployment of spring boot?

Use devtools to start hot deployment, add devtools library, set spring. devtools. restart. enabled to true in the configuration file;
use Intellij Idea editor to automatically compile or recompile manually.

20. What is spring cloud?

Spring cloud is an ordered collection of a series of frameworks. It uses the development convenience of spring boot to cleverly simplifies the development of distributed system infrastructure, such as service discovery registration, configuration center, message bus, load balancing, circuit breakers, data monitoring, etc., can all be done in spring boot development style To one-click launch and deployment.

21. What is the function of spring cloud circuit breaker?

In a distributed architecture, the function of the circuit breaker mode is similar. When a service unit fails (similar to a short circuit in an electrical appliance), the fault monitoring of the circuit breaker (similar to a blown fuse) returns an error response to the caller Instead of waiting for a long time. In this way, the thread will not be occupied for a long time due to calling the fault service, and the spread of the fault in the distributed system will be avoided.

22. What are the core components of spring cloud?

Eureka: The service is registered with discovery.
Feign: Based on the dynamic proxy mechanism, according to the annotation and the selected machine, splicing the request url address to initiate the request.
Ribbon: To achieve load balancing, choose one from multiple machines in a service.
Hystrix: Provides a thread pool, and different services use different thread pools, which realizes the isolation of different service calls and avoids the problem of service avalanche.
Zuul: Gateway management, the Zuul gateway forwards the request to the corresponding service.
Hibernate

23. Why use hibernate?

Hibernate is an encapsulation of jdbc, which greatly simplifies the tedious and repetitive code of the data access layer.
Hibernate is an excellent ORM implementation, which simplifies the coding function of the DAO layer to a great extent.
Can easily carry out database transplantation.
Provides a caching mechanism, which is efficient for program execution changes.

24. What is the ORM framework?

ORM (Object Relation Mapping) object relational mapping is to map relational data in the database into objects in the program.
The advantages of using ORM: improved development efficiency, reduced development costs, simpler and more object-oriented development, and stronger portability.

25. How to view the printed SQL statement in the console in hibernate?

Set hibernate. show_SQL to true in Config. But it is not recommended to turn it on, as it will reduce the efficiency of the program.

26. How many query methods does hibernate have?

Three types: hql, native SQL, and conditional query Criteria.

27. Can hibernate entity classes be defined as final?

The entity class can be defined as a final class, but in this case, the delayed association in the hibernate proxy mode cannot be used to provide performance, so it is not recommended to define the entity class as final.

28. What is the difference between using Integer and int for mapping in hibernate?

The Integer type is an object, and its value is allowed to be null, while int belongs to the basic data type, and the value cannot be null.

29. How does hibernate work?

Read and parse the configuration file.
Read and parse the mapping file and create a SessionFactory.
Open Session.
Create a transaction.
Perform persistence operations.
Commit the transaction.
Close the Session.
Close SessionFactory.

30. The difference between get() and load()?

When querying data, if there is no object specified by OID, get() returns null; load() returns a proxy object.
load() supports lazy loading; get() does not support lazy loading.

31. Tell me about hibernate's caching mechanism?

Commonly used hibernate caches include level one cache and level two cache:
level one cache: also called session cache, it is only valid within the scope of the session, does not require user intervention, it is maintained by hibernate itself, you can clear the object cache through: evict(object) ;Clear() clears all caches in the first-level cache; flush() flushes out the cache;
second-level cache: application-level cache, valid in all sessions, supports configuration of third-party caches, such as EhCache.

32. What are the statuses of hibernate objects?

Temporary/transient state: the object that is directly new, the object has not been persisted (not stored in the database), and is not managed by the Session.
Persistent state: When the save/saveOrupdate/get/load/list methods of Session are called, the object is the persistent state.
Free state: The object is free after the Session is closed.

33. What is the difference between getCurrentSession and openSession in hibernate?

getCurrentSession will bind the current thread, while openSession will not.
The getCurrentSession transaction is controlled by Spring and does not need to be closed manually, while openSession requires us to manually open and commit the transaction.

34. Does hibernate entity class have to have a parameterless constructor? why?

Each entity class in hibernate must provide a parameterless constructor, because the hibernate framework uses reflection api to create an instance of the entity class by calling ClassnewInstance(). If there is no parameterless constructor, an exception will be thrown.
MyBatis

35. What is the difference between #{} and in MyBatis? #Is pre-compiled processing, what is the difference between {}? #{} is pre-compilation processing, what is the difference?

This # is pre-compilation processing, and {} is character replacement. When using #{}, MyBatis will replace #{} in SQL with "?" and coordinate with the set method of PreparedStatement to assign values, which can effectively prevent SQL injection and ensure the safe operation of the program.

36. How many paging methods does MyBatis have?

Paging mode: logical paging and physical paging.
Logical paging: Use the RowBounds that comes with MyBatis for paging. It queries a lot of data at once, and then retrieves it in the data.
Physical paging: Hand-write SQL paging by yourself or use the paging plug-in PageHelper to query the form of the specified number of paging data in the database.

37. Does RowBounds query all results at once? why?

RowBounds surface is to retrieve data in "all" data, in fact, it is not to query all the data at once, because MyBatis is a package of jdbc, there is a Fetch Size configuration in the jdbc driver, which stipulates that the maximum query from the database each time How many pieces of data, if you want to query more data, it will query more data when you execute next(). It's like you go to the ATM to withdraw 10,000 yuan, but the ATM can withdraw up to 2500 yuan each time, so you have to withdraw 4 times to get the money out. But for jdbc, when you call next(), it will automatically complete the query for you. The benefits of this can effectively prevent memory overflow.
Fetch Size official documents: http://t. cn/EfSE2g3

38. What is the difference between logical paging and physical paging in MyBatis?

Logical paging is to query a lot of data at once, and then retrieve the paged data in the results. The disadvantage of this is that it consumes a lot of memory, has the risk of memory overflow, and puts a lot of pressure on the database.
Physical paging is to query a specified number of data from the database, which makes up for all the shortcomings of all the data found at one time, such as the need for a large amount of memory, and the pressure on database queries.

39. Does MyBatis support lazy loading? What is the principle of lazy loading?

MyBatis supports lazy loading, just set lazyLoadingEnabled=true.
The principle of lazy loading is to trigger loading when called, rather than loading information when initializing. For example, when calling a. getB(). getName(), at this time it is found that the value of a. getB() is null. At this time, the SQL associated with the B object saved in advance will be triggered separately, and B will be queried first, and then a. setB(b), and then call a. getB(). getName() to have a value. This is the basic principle of lazy loading.

40. Tell me about the primary cache and secondary cache of MyBatis?

Level 1 cache: HashMap local cache based on PerpetualCache. Its life cycle is consistent with SQLSession. If there are multiple SQLSessions or database operations in a distributed environment, dirty data may occur. After Session flush or close, all Caches in the Session will be emptied, and the first level cache is enabled by default.
Second-level cache: HashMap local cache based on PerpetualCache. The difference is that its storage scope is Mapper level. If multiple SQLSessions need to share the cache, you need to use the second-level cache, and the second-level cache can customize the storage source , Such as Ehcache. The second-level cache is not turned on by default. To enable 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).
Start the second-level cache data query process: second-level cache -> first-level cache -> database.
Cache update mechanism: When a certain scope (first-level cache Session/second-level cache Mapper) performs a C/U/D operation, by default, all caches in select under this scope will be cleared.

41. What are the differences between MyBatis and hibernate?

Flexibility: MyBatis is more flexible, you can write SQL statements yourself, which is more convenient to use.
Portability: MyBatis has a lot of SQL written by itself, because the SQL of each database can be different, so the portability is relatively poor.
Learning and use threshold: MyBatis is relatively simple to get started, and the use threshold is also lower.
Second-level cache: hibernate has a better second-level cache, and its second-level cache can be replaced by a third-party second-level cache.

42. What executors (Executor) does MyBatis have?

MyBatis has three basic Executor executors:
SimpleExecutor: opens a Statement object every time an update or select is executed, and closes the Statement object as
soon as it is used up; ReuseExecutor: executes update or select, uses SQL as the key to find the Statement object, and uses it if it exists. It is created if it exists, and the Statement object is not closed after use, but placed in the Map for the next use. In short, it is to reuse the Statement object;
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, and each Statement object waits for executeBatch() batch processing after addBatch() is completed, which is the same as jdbc batch processing.

43. What is the realization principle of the 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's interception method, then rewrite the SQL, and add the corresponding physical paging statement and physical paging parameters according to the dialect dialect.

44. How to write a custom plug-in for MyBatis?

Implementation principle of
custom plug-in MyBatis custom plug-in intercepts the four major objects of MyBatis (Executor, StatementHandler, ParameterHandler, ResultSetHandler):
Executor: intercepts the internal executor, which is responsible for calling the StatementHandler to operate the database, and automatically mapping the result set through the ResultSetHandler. In addition, it also handles the operation of the second-level cache;
StatementHandler: intercepts the processing of SQL grammar construction, it is the object of MyBatis to execute SQL scripts directly with the database, and it also implements the first-level cache of MyBatis;
ParameterHandler: intercepts the processing of parameters;
ResultSetHandler: Intercept the processing of the result set.
Custom plug-in implementation key
MyBatis plug-in must implement the Interceptor interface, and the methods contained in the interface are as follows:

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

The setProperties method can configure custom related properties when configuring the plug-in in MyBatis, that is: the parameter configuration of the interface implementation object; the
plugin method is used by the plug-in to encapsulate the target object, through this method we can return the target object itself, or return A proxy can decide whether to intercept and then decide what kind of target object to return. The official example is provided: return Plugin. wrap(target, this); The
intercept method is the method to be executed when intercepting.
Custom plug-in implementation example
Official plug-in implementation:

@Intercepts({
    
    @Signature(type = Executor. class, method = “query”,
args = {
    
    MappedStatement. class, Object. class, RowBounds. class, ResultHandler. class})})
public class TestInterceptor 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);
}
}

45. What is the difference between spring mvc and struts?

Interception level: struts2 is class-level interception; spring mvc is method-level interception.
Data independence: The methods of spring mvc are basically independent, request and response data are exclusively shared, request data is obtained through parameters, and the processing results are returned to the framework through ModelMap. Variables are not shared between methods; while struts2 does not share variables between methods. It is also independent, but all its action variables are shared, which will not affect the operation of the program, but it brings us some trouble when coding and reading the program.
Interception mechanism: Struts2 has its own interceptor mechanism, and spring mvc uses an independent aop method, which results in a larger amount of configuration files for struts2 than spring mvc.
Support for ajax: spring mvc integrates ajax, all ajax is very convenient to use, only an annotation @ResponseBody can be achieved; and struts2 generally need to install plug-ins or write code yourself.

5. Finally:

In view of the fact that many people have been interviewing recently, I have also compiled a lot of interview topic materials here, as well as experience from other major companies. Hope it helps everyone.

The answers to the interview questions below are organized into document notes. I also sorted out some interview materials & the latest interview questions collected by some big companies in 2020 (all organized into documents, a small part of the screenshots), if necessary, you can click to enter the secret CSDN

Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/banzhuanhu/article/details/109299458