Spring interview knowledge points / the most complete Spring interview questions and answers

Spring overview

1. What is spring?

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

2. What are the benefits of using Spring framework?

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 life cycle and configuration of objects in the application.

MVC framework : Spring's WEB framework is a well-designed framework and a good alternative to the Web framework.

Transaction management: Spring provides a continuous transaction management interface, which can be extended from local transactions to global transactions (JTA).

Exception handling: Spring provides a convenient API to convert specific technology-related exceptions (such as thrown by JDBC, Hibernate or JDO) into consistent unchecked exceptions.

3. What modules does Spring consist of?

The following are the basic modules of the Spring framework:

Core module

Bean module

Context module

Expression Language module

JDBC module

ORM module

OXM module

Java Messaging Service(JMS) module

Transaction module

Web module

Web-Servlet module

Web-Struts module

Web-Portlet module

4. Core container (application context) module.

This is the basic Spring module that provides the basic functions of the spring framework. BeanFactory is the core of any spring-based application. The Spring framework is built on this module, which makes Spring a container.

5. BeanFactory-BeanFactory implementation examples.

Bean factory is an implementation of the factory pattern, which provides the function of inversion of control to separate the configuration and dependencies of the application from the real application code.

The most commonly used BeanFactory implementation is the XmlBeanFactory class.

6、XMLBeanFactory 

The most commonly used is org.springframework.beans.factory.xml.XmlBeanFactory, which loads beans according to the definition in the XML file. The container reads configuration metadata from an XML file and uses it to create a fully configured system or application.

7, explain the AOP module

The AOP module is used for aspect-oriented development of Spring applications sent to us. A lot of support is provided by the AOP Alliance, which ensures the commonality of Spring and other AOP frameworks. This module brings metadata programming to Spring.

8. Explain the JDBC abstraction and DAO module.

By using the JDBC abstraction and DAO module, the database code is kept concise, and problems caused by the wrong closing of database resources can be avoided. It provides a unified exception access layer on top of the error information of various databases. It also uses Spring's AOP module to provide transaction management services for objects in Spring applications.

9. Explain the object/relational mapping integration module.

Spring supports the use of an object/relational mapping (ORM) tool on top of direct JDBC by providing an ORM module. Spring supports the integration of mainstream ORM frameworks such as Hiberate, JDO and iBATIS SQL Maps. Spring's transaction management also supports all the above ORM frameworks and JDBC.

10. Explain the WEB module.

Spring's WEB module is built on the basis of the application context module to provide a context suitable for web applications. This module also includes support for a variety of web-oriented tasks, such as transparently handling multiple file upload requests and binding of program-level request parameters to your business objects. It also has support for Jakarta Struts.

12. Spring configuration file

The Spring configuration file is an XML file, this file contains class information, describes how to configure them, and how to call each other.

13. What is the Spring IOC container?

Spring IOC is responsible for creating objects, managing objects (through dependency injection (DI), assembling objects, configuring objects, and managing the entire life cycle of these objects).

14. What are the advantages of IOC?

IOC or dependency injection minimizes the amount of application code. It makes the application easy to test, unit testing no longer requires singleton and JNDI lookup mechanism. The least cost and the least intrusiveness make loose coupling possible. The IOC container supports hungry Chinese initialization and lazy loading when loading services.

15.What is the usual implementation of ApplicationContext?

FileSystemXmlApplicationContext: This container loads the definition of beans from an XML file, and the full path name of the XML Bean configuration file must be provided to its constructor.

ClassPathXmlApplicationContext: This container also loads the definition of beans from an XML file. Here, you need to set the classpath correctly because this container will find the bean configuration in the classpath.

WebXmlApplicationContext: This container loads an XML file, which defines all beans of a WEB application.

16. What is the difference between Bean Factory and Application Contexts?

Application contexts provide a way to process text messages. A common approach is to load file resources (such as mirrors), which can publish events to beans registered as listeners. In addition, the operations performed on the container or objects within the container that have to be processed programmatically by the bean factory can be processed in a declarative manner in Application contexts. Application contexts implements the MessageSource interface, which implements a pluggable way to obtain localized messages.

17. What does a Spring application look like?

An interface that defines some functions.

This implementation includes properties, its Setters, getter methods and functions, etc.

Spring AOP。

Spring's XML configuration file.

Client programs that use the above functions.

Dependency injection

18. What is dependency injection in Spring?

Dependency injection, an aspect of IOC, is a common concept, and it has many explanations. The concept is that you don't need to create an object, but only need to describe how it is created. You don't assemble your components and services directly in the code, but you need to describe which components need which services in the configuration file, and then a container (IOC container) is responsible for assembling them.

19. What are the different types of IOC (dependency injection) methods?

Constructor dependency injection: Constructor dependency injection is realized by triggering the constructor of a class by the container. The class has a series of parameters, and each parameter represents a dependency on other classes.

Setter method injection: Setter method injection means that after the container instantiates the bean by calling the no-parameter constructor or the no-parameter static factory method, the setter method of the bean is called, which implements setter-based dependency injection.

20. Which method of dependency injection do you recommend, constructor injection or Setter method injection?

You can use two dependency methods, constructor injection and Setter method injection. The best solution is to use constructor parameters to implement mandatory dependencies and setter methods to implement optional dependencies.

Spring Beans

21. What are Spring beans?

Spring beans are those java objects that form the backbone of a Spring application. They are initialized, assembled, and managed by the Spring IOC container. These beans are created by metadata configured in the container. For example, it is defined in the form of <bean/> in an XML file.

The beans defined by the Spring framework are all singleton beans. There is an attribute "singleton" in the bean tag. If it is assigned TRUE, the bean is a singleton, otherwise it is a prototype bean. The default is TRUE, so all beans in the Spring framework are singletons by default.

22. What does a Spring Bean definition include?

The definition of a Spring Bean contains all the configuration metadata that the container must know, including how to create a bean, its life cycle details and its dependencies.

23. How to provide configuration metadata to the Spring container?

There are three important ways to provide configuration metadata to the Spring container.

XML configuration file.

Annotation-based configuration.

Java-based configuration.

24. How do you define the scope of a class? 

When defining a <bean> in Spring, we can also declare a scope for the bean. It can be defined by the scope attribute in the bean definition. For example, when Spring wants to produce a new bean instance every time it is needed, the scope property of the bean is specified as prototype. On the other hand, a bean must return the same instance every time it is used, and the scope attribute of this bean must be set to singleton.

25. Explain the scope of several beans supported by Spring.

The Spring framework supports the following five bean scopes:

singleton: The  bean has only one instance in each Spring ioc container.

Prototype : A bean definition can have multiple instances.

request : Each http request will create a bean, and the scope is only valid in the context of a web-based Spring ApplicationContext.

session : In an HTTP Session, a bean definition corresponds to an instance. This scope is only valid in the case of web-based Spring ApplicationContext.

global-session : In a global HTTP Session, a bean definition corresponds to an instance. This scope is only valid in the case of web-based Spring ApplicationContext.

The scope of the default Spring bean is Singleton.

26. Is the singleton bean in the Spring framework thread safe?

No, singleton beans in the Spring framework are not thread-safe.

27. Explain the life cycle of beans in the Spring framework.

The Spring container reads the bean definition from the XML file and instantiates the bean.

Spring fills in all properties according to the definition of the bean.

If the bean implements the BeanNameAware interface, Spring passes the bean ID to the setBeanName method.

If the Bean implements the BeanFactoryAware interface, Spring passes beanfactory to the setBeanFactory method.

If there are any BeanPostProcessors associated with the bean, Spring will call them in the postProcesserBeforeInitialization() method.

If the bean implements IntializingBean, call its afterPropertySet method. If the bean declares an initialization method, call this initialization method.

If there are BeanPostProcessors associated with beans, the postProcessAfterInitialization() method of these beans will be called.

If the bean implements DisposableBean, it will call the destroy() method.

28. What are the important bean life cycle methods? Can you overload them?

There are two important bean life cycle methods. The first is setup, which is called when the container loads the bean. The second method is teardown, which is called when the container unloads the class.

The bean tag has two important attributes (init-method and destroy-method). With them you can customize the initialization and logout methods yourself. They also have corresponding annotations (@PostConstruct and @PreDestroy).

29. What is Spring's internal bean?

When a bean is only used as a property of another bean, it can be declared as an inner bean. In order to define the inner bean, in Spring's XML-based configuration metadata, it can be specified in <property/> or <constructor-arg The <bean/> element is used in the /> element. The inner beans are usually anonymous, and their scope is generally prototype.

30. How to inject a java collection in Spring?

Spring provides the following collections of configuration elements:

The <list> type is used to inject a list of values, allowing the same value.

The <set> type is used to inject a set of values, and the same value is not allowed.

The <map> type is used to inject a set of key-value pairs. Both keys and values ​​can be of any type.

The <props> type is used to inject a set of key-value pairs, and both keys and values ​​can only be of String type.

31. What is bean assembly? 

Assembly, or bean assembly, refers to assembling beans together in the Spring container, provided that the container needs to know the dependencies of the beans and how to assemble them together through dependency injection.

32. What is automatic assembly of bean?

The Spring container can automatically assemble the cooperating beans, which means that the container does not need <constructor-arg> and <property> configuration, and can automatically handle the cooperation between beans through the Bean factory.

33. Explain different ways of automatic assembly.

There are five automatic assembly methods that can be used to instruct the Spring container to use automatic assembly for dependency injection.

no : The default method is not to perform automatic assembly, and to perform assembly by explicitly setting the ref attribute.

byName: Automatic assembly through the parameter name. The Spring container finds in the configuration file that the autowire attribute of the bean is set to byname, and then the container tries to match and assemble the bean with the same name as the bean attribute.

byType: Through the automatic assembly of the parameter type, the Spring container finds in the configuration file that the autowire attribute of the bean is set to byType, and then the container tries to match and assemble a bean of the same type as the attribute of the bean. If multiple beans meet the conditions, an error is thrown.

Constructor : This method is similar to byType, but it must be provided to the constructor parameters. If there is no determined constructor parameter type with parameters, an exception will be thrown.

autodetect: First try to use the constructor to auto-assemble, if it does not work, use the byType method.

34. What are the limitations of automatic assembly?

The limitations of automatic assembly are:

Rewrite : You still need to use <constructor-arg> and <property> configuration to define dependencies, which means that you always have to rewrite autowiring.

Basic data types : You cannot automatically assemble simple attributes, such as basic data types, String strings, and classes.

Fuzzy feature: Automatic assembly is not as accurate as explicit assembly. If possible, explicit assembly is recommended.

35. Can you inject a null and an empty string into Spring?

can.

Spring annotation

36. What is Java-based Spring annotation configuration? Give some annotation examples.

Java-based configuration allows you to do most of your Spring configuration with the help of a small amount of Java annotations instead of through XML files.

Take the @Configuration annotation as an example. It is used to mark that a class can be used as a bean definition and used by the Spring IOC container. Another example is the @Bean annotation, which indicates that this method will return an object, which is registered as a bean in the Spring application context.

37. What is the annotation-based container configuration?

Compared to XML files, annotation-type configuration relies on assembly of components through bytecode metadata, rather than angle bracket declarations.

Developers use annotations on the corresponding classes, methods, or attributes to configure directly in the component class instead of using xml to express the bean assembly relationship.

38. How to open annotation assembly?

Annotation assembly is not enabled by default. In order to use annotation assembly, we must configure the <context:annotation-config/> element in the Spring configuration file.

39, @Required annotation

This annotation indicates that bean properties must be set during configuration, through an explicit property value defined by a bean or through automatic assembly. If the bean property annotated with @Required is not set, the container will throw a BeanInitializationException.

40, @Autowired annotation

The @Autowired annotation provides more fine-grained control, including where and how to complete the automatic assembly. Its usage is the same as @Required, modifying setter methods, constructors, attributes or PN methods with arbitrary names and/or multiple parameters.

41, @Qualifier annotation

When there are multiple beans of the same type but only one needs to be automatically assembled, use the @Qualifier annotation and @Autowire annotation in combination to eliminate this confusion and specify the exact bean that needs to be assembled.

Spring data access

42. How to use JDBC more effectively in the Spring framework? 

Using the SpringJDBC framework, the cost of resource management and error handling will be reduced. So developers only need to write statements and queries to access data from data. JDBC can also be used more effectively with the help of the template classes provided by the Spring framework. This template is called JdbcTemplate (see here for examples)

43 、 JdbcTemplate

The JdbcTemplate class provides many convenient methods to solve such as converting database data into basic data types or objects, executing written or callable database operation statements, and providing custom data error handling.

44, Spring's support for DAO

Spring's support for Data Access Objects (DAO) is designed to simplify its use in conjunction with data access technologies such as JDBC, Hibernate or JDO. This allows us to easily switch the persistence layer. Don't worry about catching exceptions specific to each technology when coding.

45. How to access Hibernate by using Spring? 

There are two ways to access Hibernate in Spring:

Inversion of control Hibernate Template and Callback.

Inherit HibernateDAOSupport to provide an AOP interceptor.

46. ​​ORM supported by Spring

Spring supports the following ORMs:

Hibernate

iBatis

JPA (Java Persistence API)

TopLink

JDO (Java Data Objects)

OJB

47. How to combine Spring and Hibernate through HibernateDaoSupport?

Use Spring's SessionFactory to call LocalSessionFactory. The integration process is divided into three steps:

配置the Hibernate SessionFactory。

Inherit HibernateDaoSupport to implement a DAO.

Assemble in AOP-supported transactions.

48. Types of transaction management supported by Spring

Spring supports two types of transaction management:

Programmatic transaction management : This means that you manage transactions programmatically, which brings you great flexibility but is difficult to maintain.

Declarative transaction management: This means that you can separate business code and transaction management, and you only need to use annotations and XML configuration to manage transactions.

49. What are the advantages of Spring framework transaction management?

It provides a constant programming model for different transaction APIs such as JTA, JDBC, Hibernate, JPA and JDO.

It provides a set of simple APIs for programmatic transaction management instead of some complex transaction APIs such as

It supports declarative transaction management.

It is well integrated with Spring's various data access abstraction layers.

50. Which type of transaction management do you prefer?

Most users of the Spring framework choose declarative transaction management because it has the least impact on the application code, so it is more in line with the idea of ​​a non-intrusive lightweight container. Declarative transaction management is better than programmatic transaction management, although it is a bit less flexible than programmatic transaction management (which allows you to control transactions through code).

Spring aspect-oriented programming (AOP)

51, explain AOP

Aspect-oriented programming, or AOP, is a programming technique that allows programs to be modularized to cut concerns horizontally, or to cut typical divisions of responsibilities, such as logging and transaction management.

52, Aspect

The core of AOP is the aspect, which encapsulates the common behaviors of multiple classes into a reusable module that contains a set of APIs to provide cross-cutting functions. For example, a logging module can be referred to as the AOP aspect of logging. According to different requirements, an application can have several aspects. In Spring AOP, aspects are implemented by classes annotated with @Aspect.

52. What is the difference between focus and crosscutting focus in Spring AOP?

The focus is the behavior of a module in the application. A focus may be defined as a function we want to implement.
The cross-cutting concern is a concern. This concern is a function that the entire application will use and affects the entire application, such as logging, security, and data transmission, which are required by almost every module of the application. So these are all crosscutting concerns.

54. Connection point

The connection point represents a certain location of an application, where we can insert an AOP aspect, which is actually the location where the application executes Spring AOP.

55. Notification

Notification is an action to be done before or after the method is executed. It is actually a code segment triggered by the SpringAOP framework when the program is executed.

Five types of notifications can be applied to Spring aspects:

before : pre-notification, which is called before a method is executed.

after: A notification called after  the method is executed, regardless of whether the method is executed successfully or not.

after-returning:  A notification executed only when the method is successfully completed.

after-throwing:  Notification executed when the method exits by throwing an exception.

around:  Notifications called before and after method execution.

56, the cut point

The entry point is a connection point or set of points where notification will be performed. The entry point can be specified by expression or matching.

57. What is introduction? 

The introduction allows us to add new methods and properties to existing classes.

58. What is the target object? 

The object notified by one or more aspects. It is usually a proxy object. Also refers to the advised object.

59.What is an agency?

A proxy is an object created after notifying the target object. From the perspective of the client, the proxy object and the target object are the same.

60. How many different types of automatic agents are there?

BeanNameAutoProxyCreator

DefaultAdvisorAutoProxyCreator

Metadata autoproxying

61. What is weaving. What are the differences in weaving applications?

Weaving is the process of connecting aspects to other application types or objects or creating a notified object.

Weaving can be done at compile time, load time, or run time.

62. Explain the realization of the aspect based on XML Schema.

In this case, the aspect is implemented by conventional classes and XML-based configuration.

63. Explain the implementation of annotation-based aspects

In this case (based on the implementation of @AspectJ), the style of the aspect declaration involved is consistent with the ordinary java class with java5 annotations.

Spring 的MVC

64. What is Spring's MVC framework?

Spring is equipped with a full-featured MVC framework for building web applications. Spring can be easily integrated with other MVC frameworks, such as Struts. Spring's MVC framework uses inversion of control to clearly isolate business objects from control logic. It also allows to bind request parameters to business objects in a declarative manner.

65、DispatcherServlet

Spring's MVC framework is designed around DispatcherServlet, which is used to process all HTTP requests and responses.

66、WebApplicationContext

WebApplicationContext inherits ApplicationContext and adds some unique features necessary for WEB applications. It is different from the general ApplicationContext because it can handle themes and find the associated servlet.

67. What is the controller of the Spring MVC framework?

The controller provides a behavior to access the application, which is usually implemented through a service interface. The controller parses the user input and transforms it into a model that is presented to the user by the view. Spring implements a control layer in a very abstract way, allowing users to create controllers for multiple purposes.

68, @Controller annotation

The annotation indicates that the class plays the role of the controller, and Spring does not require you to inherit any other controller base classes or reference the Servlet API.

69, @RequestMapping annotation

The annotation is used to map a URL to a class or a specific method.

Guess you like

Origin blog.csdn.net/bj_chengrong/article/details/101100930