A roundup of interview questions and answers about Spring

69 Spring Interview Questions and Answers

Original address Translator: Deep Sea ([email protected]) Proofreading: Fang Tengfei

 

content

Spring overview

dependency injection

Spring beans

Spring annotations

Spring Data Access

Spring Aspect Oriented Programming (AOP)

Spring MVC

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 Spring Framework goal is to simplify Java enterprise application development and promote good programming practices through a POJO-based programming model.

 

 

2. What are the benefits of using the Spring framework?

 

Lightweight: Spring is lightweight, the basic version is about 2MB.

Inversion of Control: Spring achieves loose coupling through Inversion of Control, where 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 alternative to a 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 technology-specific exceptions (such as those 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 functionality of the Spring Framework, and the BeanFactory is the core of any Spring-based application. The Spring Framework is built on top of this module, which makes Spring a container.

 

5. BeanFactory – BeanFactory implementation example.

 

A bean factory is an implementation of the factory pattern that provides inversion of control functionality to separate application configuration and dependencies from the actual 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 as defined in an 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 to send our Spring applications for aspect-oriented development, and a lot of support is provided by the AOP Alliance, which ensures the commonality between Spring and other AOP frameworks. This module brings metadata programming into Spring.

 

8. Explain the JDBC abstraction and the DAO module.

 

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

 

9. Explain the Object/Relational Mapping Integration Module.

 

Spring supports us to use an object/relational mapping (ORM) tool on top of direct JDBC by providing ORM modules. Spring supports integration of mainstream ORM frameworks such as Hiberate, JDO and iBATIS SQL Maps. Spring's transaction management also supports all of 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, providing a context suitable for web applications. This module also includes support for various web-oriented tasks, such as transparently handling multiple file upload requests and binding application-level request parameters to your business objects. It also has support for Jakarta Struts.

 

12. Spring configuration file

 

A Spring configuration file is an XML file that 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 lifecycle of those objects.

 

14. What are the advantages of an IOC?

 

IOC or Dependency Injection minimizes the code size of the application. It makes the application easy to test, unit testing no longer needs singleton and JNDI lookup mechanism. Loose coupling is achieved with minimal effort and minimal intrusiveness. The IOC container supports hungry initialization and lazy loading when loading services.

 

15. What is the usual implementation of ApplicationContext?

 

FileSystemXmlApplicationContext : This container loads bean definitions from an XML file. The full pathname of the XML Bean configuration file must be provided to its constructor.

ClassPathXmlApplicationContext: This container also loads the bean definitions from an XML file, here, you need to set the classpath correctly because the container will look for the bean configuration in the classpath.

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

16. What is the difference between Bean factories and Application contexts?

 

Application contexts provide a way to handle text messages, a common practice is to load file resources (such as images), which can publish events to beans registered as listeners. In addition, operations performed on the container or objects within the container that have to be handled programmatically by the bean factory can be handled declaratively in Application contexts. Application contexts implement the MessageSource interface, the implementation of which provides methods to obtain localized messages in a pluggable manner.

 

17. What does a Spring application look like?

 

An interface that defines some functionality.

This implementation includes the property, its setter, getter methods and functions, etc.

Spring AOP。

Spring's XML configuration file.

A client program that uses the above functions.

dependency injection

18. What is Spring's Dependency Injection?

 

Dependency injection, an aspect of IOC, is a general concept that has many interpretations. The concept is that you don't create an object, you just describe how it is created. You don't assemble your components and services directly in the code, but 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 implemented by the container triggering the constructor of a class that has a series of parameters, each parameter representing a dependency on other classes.

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

20. Which Dependency Injection method do you recommend, Constructor Injection or Setter Method Injection?

 

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

 

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 from 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 a property "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 contain?

 

A Spring Bean definition contains all the configuration metadata that the container must know, including how to create a bean, its lifecycle 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 through the scope attribute in the bean definition. For example, when Spring wants to produce a new bean instance each time it is needed, the bean's scope property is specified as prototype. On the other hand, a bean must return the same instance every time it is used, and the bean's scope property 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 per Spring ioc container.

prototype: A bean definition can have multiple instances.

request: A bean is created for each http request. This 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 context of a 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 context of a web-based Spring ApplicationContext.

The default Spring bean scope is Singleton.

 

26. Are singleton beans in Spring framework thread safe?

 

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

 

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

 

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

Spring populates all properties according to the bean definition.

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

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

If there are any BeanPostProcessors associated with the bean, Spring calls them within the postProcesserBeforeInitialization() method.

If the bean implements IntializingBean, its afterPropertySet method is called, and if the bean declares an initialization method, this initialization method is called.

If there are BeanPostProcessors associated with the bean, 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 lifecycle methods? Can you overload them?

 

There are two important bean lifecycle 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 properties (init-method and destroy-method). With them you can customize initialization and logout methods yourself. They also have corresponding annotations (@PostConstruct and @PreDestroy).

 

29. What are Spring's internal beans?

 

When a bean is only used as a property of another bean, it can be declared as an inner bean. To define an inner bean, in Spring's XML-based configuration metadata, either <property/> or <constructor-arg The <bean/> element is used inside 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 sets 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, no identical values ​​are 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, both keys and values ​​can only be of type String.

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 bean's dependencies and how to assemble them together through dependency injection.

 

32. What is autowiring of beans?

 

The Spring container can autowire 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 autowiring.

 

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

 

no: The default is to not autowire, and to wire by explicitly setting the ref attribute.

byName: Through the parameter name autowiring, the Spring container finds that the bean's autowire property is set to byname in the configuration file, and then the container tries to match, assemble, and the bean's properties have the same name as the bean.

byType: Through parameter type autowiring, the Spring container finds that the bean's autowire property is set to byType in the configuration file, and then the container tries to match, wire and match the bean's properties with the same type of bean. Throws an error if more than one bean matches the condition.

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

autodetect: first try to use the constructor to autowire, if it doesn't work, use the byType method.

34. What are the limitations of automatic assembly?

 

The limitations of autowiring are:

 

Override: You still need to define dependencies with <constructor-arg> and <property> configuration, which means always override autowiring.

Primitive data types: You cannot autowire simple properties such as primitive data types, Strings, and classes.

Fuzzy feature: Autowiring is not as precise as explicit wiring, it is recommended to use explicit wiring if possible.

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

 

Can.

 

Spring annotations

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

 

Java-based configuration allows you to do most of your Spring configuration with the help of a few Java annotations rather than 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 that is registered as a bean into the Spring application context.

 

37. What is annotation-based container configuration?

 

In contrast to XML files, annotated configuration relies on assembling components via bytecode metadata, rather than angle-bracketed declarations.

 

Instead of using xml to express the bean assembly relationship, developers can configure directly in the component class by using annotations on the corresponding classes, methods or properties.

 

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 the bean property must be set at configuration time, either through an explicit property value in a bean definition or through autowiring. If the @Required annotated bean property is not set, the container will throw a BeanInitializationException.

 

40. @Autowired annotation

 

The @Autowired annotation provides more fine-grained control, including where and how autowiring is done. It is used in the same way as @Required, to decorate setter methods, constructors, properties, 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 autowired, use the @Qualifier annotation in conjunction with the @Autowire annotation to eliminate this confusion, specifying the exact bean that needs to be wired.

 

Spring Data Access

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

 

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

 

43. JdbcTemplate

 

The JdbcTemplate class provides many convenient methods 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 support for DAO

 

Spring's support for Data Access Objects (DAO) is designed to simplify its use with data access technologies such as JDBC, Hibernate or JDO. This allows us to easily switch persistence layers. Code without worrying about catching exceptions specific to each technology.

 

45. How to access Hibernate using Spring? 

 

There are two ways to access Hibernate in Spring:

 

Inversion of Control Hibernate Template and Callback.

Inheriting HibernateDAOSupport provides an AOP interceptor.

46. ​​ORMs 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?

 

Call LocalSessionFactory with Spring's SessionFactory. The integration process is a three-step process:

 

配置the Hibernate SessionFactory。

Inherit HibernateDaoSupport to implement a DAO.

Assemble in AOP-backed transactions.

48. Transaction management types supported by Spring

 

Spring supports two types of transaction management:

 

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

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

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

 

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

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

It supports declarative transaction management.

It integrates well 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 application code and is therefore more in line with the idea of ​​a non-intrusive lightweight container. Declarative transaction management is better than programmatic transaction management, albeit with a little less flexibility 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 program modularity to cross-cut concerns, or cross-cut typical divisions of responsibilities, such as logging and transaction management.

 

52. Aspect

 

The core of AOP is the aspect, which encapsulates the common behavior 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 called an AOP aspect of logging. Depending on the needs, an application can have several aspects. In Spring AOP, aspects are implemented by classes annotated with @Aspect.

 

52. In Spring AOP, what is the difference between concerns and cross-cutting concerns?

 

A concern is the behavior of a module in an application, and a concern may be defined as a function we want to implement.

A crosscutting concern is a concern that is used by the entire 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 all cross-cutting concerns.

 

54. Connect the dots

 

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

 

55. Notice

 

A notification is an action to be done before or after a method is executed, and is actually a code segment that is triggered by the SpringAOP framework when the program is executed.

 

Spring aspects can apply five types of advice:

 

before: Pre-notification, called before a method is executed.

after: A notification called after the method execution, regardless of whether the method execution succeeded or not.

after-returning: A notification that executes only when the method completes successfully.

after-throwing: Advice that executes when the method exits with an exception thrown.

around: Advice called before and after method execution.

56. Pointcut

 

A pointcut is a join point or set of join points at which advice will be executed. Pointcuts can be specified by expressions or by matching.

 

57. What is introduction? 

 

Import allows us to add new methods and properties to existing classes.

 

58. What is the target audience? 

 

An object informed by one or more aspects. It is usually a proxy object. Also refers to the notified (advised) object.

 

59. What is a proxy?

 

A proxy is an object created after notifying the target object. From the client's perspective, the proxy object is the same as the target object.

 

60. There are several different types of automatic agents?

 

BeanNameAutoProxyCreator

 

DefaultAdvisorAutoProxyCreator

 

Metadata autoproxying

 

61. What is weaving. What is the difference between weaving applications?

 

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

 

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

 

62. Explain the implementation of aspects based on XML Schema.

 

In this case, aspects are implemented by regular classes as well as XML-based configuration.

 

63. Explain Annotation-Based Aspect Implementation

 

In this case (based on the @AspectJ implementation), the style of the aspect declaration involved is the same as that of a normal java class annotated with java5.

 

Spring 的MVC

64. What is Spring's MVC framework?

 

Spring comes 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 and control logic. It also allows declarative binding of request parameters to business objects.

 

65. DispatcherServlet

 

Spring's MVC framework is designed around the DispatcherServlet, which handles all HTTP requests and responses.

 

66. WebApplicationContext

 

WebApplicationContext inherits ApplicationContext and adds some unique functions necessary for WEB applications. It is different from general ApplicationContext because it can process themes and find associated servlets.

 

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

 

A controller provides an access to the application's behavior, which is typically implemented through a service interface. The controller parses user input and converts 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

 

This annotation indicates that this class acts as a controller, and Spring does not require you to inherit from any other controller base class or reference the Servlet API.

 

69. @RequestMapping annotation

 

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326443288&siteId=291194637