Frequently asked spring-related questions in the Java interview (55 answers included)

Source: Internet
Author: User
Tags stomp

The Spring framework is now almost a standard framework for Java WEB development. So, as a Java programmer, how much do you know about Spring's main technical points? You may want to use the questions in this article to check.

1. General questions

1.1. What are the main features of different versions of the Spring Framework?

Versionfeaturespring 2.5 was released in 2007. This is the first version that supports annotations. Spring 3.0 was released on 2009. It takes full advantage of the improvements in JAVA5 and provides support for JEE6. Spring 4.0 was released on 2013. This is the first version that fully supports JAVA8.

1.2. What is the Spring Framework?

Spring is an open-source application framework designed to reduce the complexity of application development.
It is lightweight and loosely coupled.
It has a layered architecture that allows users to select components while also providing a cohesive framework for Java EE application development.
It can integrate other frameworks, such as Structs, Hibernate, EJB, etc., so it is also called framework framework.
1.3. Enumerate the advantages of the Spring Framework.

Thanks to the layered architecture of Spring frameworks, users are free to choose the components they need.
The Spring Framework supports POJO (Plain old Java Object) programming for continuous integration and testability.
JDBC is simplified because of dependency injection and control inversion.
It is open source for free.
1.4. What are the different features of the Spring Framework?

Lightweight-Spring is lightweight in terms of both code volume and transparency.
IOC-Control reversal
AOP-aspect-oriented programming separates the application business logic from the system services for high cohesion.
Container-Spring is responsible for creating and managing the life cycle and configuration of objects (beans).
MVC-Provides a highly configurable Web application and facilitates the integration of other frameworks.
Transaction management-Provides a common abstraction layer for transaction management. Spring's transactional support can also be used in environments with fewer containers.
JDBC Exception-The Spring's JDBC Abstraction layer provides an exception hierarchy that simplifies error handling strategies.
1.5. How many modules are there in the Spring Framework, and what are they?

Spring Core Container – this layer is essentially the core of the spring Framework. It contains the following modules:
Spring Core
Spring Bean
Spel (Spring Expression Language)
Spring Context
Data Access/integration – This layer provides support for interacting with the database. It contains the following modules:
JDBC (Java DataBase Connectivity)
ORM (Object relational Mapping)
OXM (Object XML mappers)
JMS (Java Messaging Service)
Transaction
Web – This layer provides support for creating WEB applications. It contains the following modules:
Web
Web–servlet
Web–socket
Web–portlet
aop– this layer supports tangent-oriented programming
instrumentation– This layer provides support for class detection and class loader implementations.
test– this layer is supported for testing with JUnit and TestNG.
Several miscellaneous modules:
messaging– This module provides support for STOMP. It also supports the annotation programming model, which is used to route and process STOMP messages from WebSocket clients.
aspects– This module provides support for integration with AspectJ.
1.6. What is a Spring configuration file?

The Spring configuration file is an XML file. This file mainly contains class information. It describes how these classes are configured and introduced to each other. However, the XML configuration file is verbose and cleaner. If not properly planned and written, managing in large projects becomes very difficult.

1.7. What are the different components of the Spring application?

Spring applications typically have the following components:

interface-defines the function.
Bean class-It contains attributes, setter and Getter methods, functions, and so on.
Spring aspect-oriented programming (AOP)-provides feature-oriented programming for facets.
Bean configuration file-Contains information about the classes and how to configure them.
User program-it uses interfaces.
1.8. What are the ways to use Spring?

There are several ways to use Spring:

As a mature Spring Web application.
As a third-party WEB framework, use the Spring frameworks middle tier.
For remote use.
As an enterprise Java Bean, it can wrap an existing POJO (Plain old Java Objects).

If you need Java Engineering, high-performance and distributed, micro-services, Spring,mybatis,netty source data analysis of friends can add Java Advanced Group: 838498680 Group There are Ali Daniel Live interpretation technology, as well as large-scale Internet company architecture Technology video free to share to everyone.

2. Dependency Injection (IOC)

2.1. What is a Spring IOC container?

The core of the spring framework is the Spring container. Containers create objects, assemble them together, configure them, and manage their full lifecycles. The Spring container uses dependency injection to manage the components that make up the application. A container receives an object for instantiation, configuration, and assembly instructions by reading the provided configuration metadata. The metadata can be provided through Xml,java annotations or Java code.

2.2. What is Dependency injection?

In dependency injection, you do not have to create objects, but you must describe how to create them. Instead of connecting components and services directly in your code, you describe which components in the configuration file require which services. They are assembled together by the IoC container.

2.3. How many ways can you complete dependency injection?

Typically, dependency injection can be done in three ways, namely:

Constructor injection
Setter Injection
Interface Injection
In the Spring Framework, only constructors and setter injections are used.

2.4. Differentiate between constructor injection and setter injection.

Constructor injection setter injection not partially injected with partial injection does not overwrite setter property overrides setter property Any modification will create a new instance arbitrary modification does not create a new instance for setting many properties for setting a few properties

2.5. How many IOC containers are there in spring?

Beanfactory-beanfactory is like a factory class that contains a collection of beans. It instantiates the bean when requested by the client.
The Applicationcontext-applicationcontext interface extends the Beanfactory interface. It provides some additional functionality on a beanfactory basis.
2.6. Distinguish between Beanfactory and ApplicationContext.

Beanfactoryapplicationcontext It uses lazy loading it uses an instant load it uses syntax to explicitly provide resource objects it itself creates and manages resource objects that do not support internationalization support internationalization does not support dependency-based annotations

2.7. List some of the benefits of the IoC.

Some of the IoC's benefits are:

It minimizes the amount of code in the application.
It will make your application easy to test because it does not require any singleton or JNDI lookup mechanisms in the unit test case.
It facilitates loose coupling with minimal impact and minimal intrusion mechanisms.
It supports immediate instantiation and lazy loading services.
2.8. The implementation mechanism of Spring IoC.

The IoC implementation principle in Spring is the Factory mode plus reflection mechanism.

Example:

    1. Beans

3.1. What is a spring bean?

They are objects that form the backbone of the user application.
Beans are managed by the Spring IoC container.
They are instantiated, configured, assembled, and managed by the Spring IoC container.
Beans are created based on the configuration metadata that the user provides to the container.
3.2. What are the configuration methods provided by spring?

Based on XML configuration
The dependencies and services required by the bean are specified in the configuration file in XML format. These configuration files typically contain many bean definitions and application-specific configuration options. They usually start with a bean tag. For example:

<bean id= "Studentbean" class= "Org.edureka.firstSpring.StudentBean" > <property name= "name" value= "Edureka" ></property> </bean> Copy Code

Annotation-based configuration
Instead of using XML to describe the bean assembly, you can configure the Bean as the component class itself by using annotations on related classes, methods, or field declarations. By default, note Assembly is not open in the Spring container. Therefore, you need to enable it in the Spring configuration file before you use it. For example:

<beans> <context:annotation-config/> <!--bean definitions Go-here--</beans> copy Code

Java API-based configuration
The Java configuration for Spring is implemented by using @Bean and @Configuration.

@Bean annotations Play the same role as the <bean/> element.
@Configuration class allows you to define inter-Bean dependencies by simply invoking other @Bean methods in the same class.
For example:

@Configuration public class Studentconfig {@Bean public Studentbean mystudent () {return new Studentbean ();}} Copy the code

3.3. Spring supports centralized bean scope?

Spring Beans Support 5 Types of scopes:

Singleton-There is only one single instance per Spring IoC container.
Prototype-Each request results in a new instance.
Request-Every HTTP request produces a new instance, and the bean is valid only within the current HTTP request.
Session-Every HTTP request produces a new bean, and the bean is valid only within the current HTTP session.
Global-session-Similar to the standard HTTP session scope, but it only makes sense in portlet-based Web applications. The Portlet specification defines the concept of a global Session, which is shared by all the various portlets that make up a portlet Web application. The bean defined in the global session scope is limited to the lifetime of the world Portlet session. If you use the global session scope to identify the bean in the Web, the Web is automatically used as the session type.
The last three are available only if the user is using a WEB-enabled ApplicationContext.

3.4. What is the life cycle of the spring bean container?

The life cycle flow of the spring bean container is as follows:

The Spring container instantiates the bean based on the bean definition in the configuration.
Spring populates all properties with dependency injection, such as the configuration defined in the bean.
If the bean implements the Beannameaware interface, the factory calls Setbeanname () by passing the Bean's ID.
If the bean implements the Beanfactoryaware interface, the factory invokes Setbeanfactory () by passing an instance of itself.
If there is any beanpostprocessors associated with the Bean, the Preprocessbeforeinitialization () method is called.
If you specify the Init method (the Init-method property of <bean>) for the bean, it is called.
Finally, if there are any beanpostprocessors associated with the Bean, the Postprocessafterinitialization () method is called.
If the bean implements the Disposablebean interface, Destory () is called when the spring container is closed.
If you specify the Destroy method for the bean (the Destroy-method property of <bean>), it is called.

3.5. What is spring's internal bean?

A bean can be declared as an internal bean only if it is used as a property of another bean. In order to define XML-based configuration metadata for bean,spring, the use of <bean> elements is provided in <property> or <constructor-arg>. Internal beans are always anonymous, and they are always used as prototypes.

For example, suppose we have a Student class that references the person class. Here we will just create an instance of the person class and use it in Student.

Student.java public class Student {private person person,//setters and Getters} public class Person {private String NA Me Private String address; Setters and Getters} bean.xml <bean id= "Studentbean" class= "com.edureka.Student" > <property name= "Person" > <!--This is inner bean--<bean class= "Com.edureka.Person" > <property name= "name" value= "Scott" > </property> <property name= "Address" value= "Bangalore" ></property> </bean> </property > </bean> Copy Code

3.6. What is Spring assembly?

When a bean is grouped together in a Spring container, it is called an assembly or a bean assembly. The Spring container needs to know what beans are needed and how the container should use dependency injection to bind the beans together and assemble the beans.

3.7. What are the options for automatic assembly?

Spring containers can automatically assemble beans. That is, you can let Spring automatically parse the bean's collaborators by examining the contents of the beanfactory.

Different modes of automatic assembly:

No-this is the default setting, which means no automatic assembly. Assembly should be made using an explicit bean reference.
ByName-It injects an object dependency based on the name of the bean. It matches and assembles its properties with the bean defined by the same name in the XML file.
Bytype-It injects an object dependency based on the type. If the type of the property matches one of the bean names in the XML file, the property is matched and assembled.
constructor-it injects a dependency by invoking the constructor of the class. It has a large number of parameters.
AutoDetect-First the container tries to assemble using the Autowire through the constructor, and if not, it tries to assemble automatically through the bytype.
3.8. What are the limitations of automatic assembly?

Coverage possibilities-You can always use <constructor-arg> and <property> settings to specify dependencies, which will override automatic assembly.
Basic metadata types-simple attributes such as the original data type, strings, and classes cannot be automatically assembled.
Confusing nature-always prefer to use clear assembly, because automatic assembly is less precise.
4. Annotations

4.1. What is annotation-based container configuration?

Instead of using XML to describe the bean assembly, the developer moves the configuration to the component class itself by using annotations on related classes, methods, or field declarations. It can be used as an alternative to XML settings. For example:

The Java configuration for Spring is implemented by using @Bean and @Configuration.

@Bean annotation plays with
The same role as the element.
@Configuration class allows you to define inter-Bean dependencies by simply invoking other @Bean methods in the same class.
For example:

@Configuration public class Studentconfig {@Bean public Studentbean mystudent () {return new Studentbean ();}} Copy the code

4.2. How do I start the annotation assembly in spring?

By default, note Assembly is not open in the Spring container. Therefore, to use annotation-based assembly, we must enable it in the Spring configuration file by configuring the <context:annotation-config/> element.

4.3. @Component, @Controller, @Repository, what's the difference between @Service?

@Component: This marks the Java class as a bean. It is a generic stereotype of any Spring management component. Spring's component scanning mechanism can now pick it up and pull it into the application environment.
@Controller: This marks a class as a Spring Web MVC controller. The Bean labeled with it is automatically imported into the IoC container.
@Service: This annotation is the specificity of the component annotations. It does not provide any other behavior for @Component annotations. You can use @Service instead of @Component in a service-tier class because it specifies the intent in a better way.
@Repository: This annotation is a special feature of @Component annotations with similar uses and functions. It provides additional benefits for DAO. It imports DAO into the IoC container and makes the unchecked exception eligible to be converted to Spring DataAccessException.
4.4. What is the use of @Required annotations?

@Required applied to the Bean property setter method. This annotation only indicates that an explicit attribute value in the bean definition must be used at configuration time or the affected bean properties are populated with automatic assembly. If the affected bean properties have not been populated, the container throws beaninitializationexception.

Example:

public class Employee {private string name, @Required public void SetName (String name) {this.name=name;} public string G Etname () {return name;}} Copy Code

4.5. What is the use of @Autowired annotations?

@Autowired can more accurately control where and how automated assembly should be done. This annotation is used to automatically assemble beans on a setter method, a constructor, a property or method that has any name or multiple parameters. By default, it is type-driven injection.

public class Employee {private string name, @Autowired public void SetName (String name) {this.name=name;} public string GetName () {return name;}} Copy Code

4.6. What is the use of @Qualifier annotations?

When you create multiple beans of the same type and want to assemble only one of the beans using attributes, you can use @qualifier annotations and @Autowired to disambiguate by specifying which exact bean should be assembled.

For example, here we have two classes, Employee and Empaccount, respectively. In Empaccount, using @qualifier specifies that a bean with ID EMP1 must be assembled.

Employee.java public class Employee {private String name, @Autowired public void SetName (String name) {this.name=name;} public string GetName () {return name;}} Empaccount.java public class Empaccount {private Employee emp, @Autowired @Qualifier (EMP1) public void ShowName () {Syste M.out.println ("Employee name:" +emp.getname);}} Copy Code

4.7. What is the use of @RequestMapping annotations?

@RequestMapping annotations are used to map specific HTTP request methods to specific classes/methods in the controller that will handle the corresponding request. This note can be applied to two levels:

Class level: The URL of the map request
Method level: Map URLs and HTTP request methods

If you need Java Engineering, high-performance and distributed, micro-services, Spring,mybatis,netty source data analysis of friends can add Java Advanced Group: 838498680 Group There are Ali Daniel Live interpretation technology, as well as large-scale Internet company architecture Technology video free to share to everyone.

5. Data access

5.1. What is the use of spring DAO?

Spring DAO makes it easier for data access technologies such as jdbc,hibernate or JDO to work in a uniform way. This makes it easy for users to switch between persistent technologies. It also allows you to write code without having to think about capturing different exceptions for each technique.

5.2. Enumerate the exceptions thrown by Spring DAO.

5.3. What classes exist in the spring JDBC API?

JdbcTemplate
Simplejdbctemplate
Namedparameterjdbctemplate
Simplejdbcinsert
Simplejdbccall
5.4. What are the methods for using Spring to access Hibernate?

We can use Spring to access Hibernate in two ways:

Control inversion using Hibernate templates and callbacks
Extend Hibernatedaosupport and apply an AOP interceptor node
5.5. Enumerate the types of transaction management supported by spring

Spring supports two types of transaction management:

Programmatic transaction management: In this process, you manage transactions with the help of programming. It gives you great flexibility, but it's very difficult to maintain.
Declarative transaction management: Here, transaction management is decoupled from business code. Only use annotations or XML-based configuration to manage transactions.
5.6. What ORM frameworks does spring support?

Hibernate
IBatis
Jpa
Jdo
Ojb
6. AOP

6.1. What is AOP?

AOP (aspect-oriented programming), which is aspect-oriented programming, complements OOP (object-oriented programming, object-oriented programming) and provides a perspective of the abstract software architecture that differs from OOP.

In OOP, we use class as our basic unit, while the basic unit in AOP is Aspect (tangent)

6.2. What is Aspect?

Aspect consists of pointcount and advice, which contains both the definition of the crosscutting logic and the definition of the connection point. Spring AOP is the framework for implementing facets that weave the crosscutting logic defined by the facets into the connection points specified by the facets.

The focus of AOP's work is on how to enhance the knitting target's connection point, which consists of two jobs:

How to navigate to a specific joinpoint via pointcut and advice
How to write slice code in advice.
It is simple to assume that a class that uses @Aspect annotations is a tangent.

6.3. What is a tangent point (joinpoint)

Some point in time at which a program runs, such as the execution of a method, or the handling of an exception.

In Spring AOP, join points is always the point of execution of the method.

6.4. What is notification (Advice)?

The action taken by Aspect at a particular joinpoint is called Advice. Spring AOP uses a Advice as an interceptor to maintain a series of interceptors around the joinpoint.

6.5. What types of notifications are available (Advice)?

Before-these types of Advice are performed before the Joinpoint method and are configured with @Before annotation tags.
After returning-these types of Advice are executed after the connection point method is performed normally and configured with the @afterreturning annotation tag.
After throwing-these types of Advice are executed only when the Joinpoint method exits by throwing an exception and uses @AfterThrowing annotation tag configuration.
After (finally)-these types of Advice are executed after the connection point method, regardless of whether the method exit is normal or abnormal, and is configured with @After annotation tags.
Around-These types of Advice are executed before and after the connection point and are configured with @Around annotation tags.
6.6. Point out the differences between concern and cross-cutting concern in spring AOP

Concern is the behavior we want to define in a particular module of the application. It can be defined as the function we want to implement.

Cross-cutting concern is a behavior that applies to the entire application, which affects the entire application. For example, logging, security, and data transfer are issues of concern to almost every module in the application, so they are cross-cutting issues.

6.7. What are the implementations of AOP?

The techniques for implementing AOP are divided into two major categories:

Static proxies-The use of commands provided by the AOP framework to compile, which generates an AOP proxy class at compile time, and is also known as a compilation enhancement;
Compile-time weaving (special compiler Implementation)
Class load-time weaving (special class loader implementation).
Dynamic proxies-in-memory "temporary" generation of AOP dynamic proxy classes at run time is also known as runtime enhancements.
JDK Dynamic Agent
CGLIB
6.8. What is the difference between Spring AOP and AspectJ AOP?

Spring AOP is based on dynamic proxy, and AspectJ is implemented based on static proxy method.

Spring AOP supports only method-level PointCut, provides full AOP support, and supports attribute-level PointCut.

6.9. How do I understand the agents in Spring?

The object created after applying Advice to the target object is called a proxy. In the case of the client object, the target object and the proxy object are the same.

Advice + Target Object = Proxy

6.10. What is knitting (Weaving)?

To create a advice object, link to a aspect and other application type or object, called weaving (Weaving). In Spring AOP, weaving is performed at run time. Please refer to:

7. MVC

7.1. What is the use of the Spring MVC framework?

The Spring WEB MVC Framework provides model-view-controller architecture and ready-to-use components for developing flexible and loosely coupled Web applications. The MVC pattern helps to separate different aspects of an application, such as input logic, business logic, and UI logic, while providing loose coupling between all of these elements.

7.2. Describe the Dispatcherservlet workflow

The Dispatcherservlet workflow can be illustrated with a picture:

The

sends an HTTP request to the server, and the request is captured by the front controller dispatcherservlet. The
dispatcherservlet resolves the requested URL according to the configuration in-servlet.xml, obtaining the requested resource Identifier (URI). Then, based on the URI, call handlermapping to get all the related objects of the Handler configuration (including the Handler object and the interceptor corresponding to the Handler object), and finally return as a Handlerexecutionchain object.
Dispatcherservlet Select a suitable handleradapter based on the handler obtained. (Note: If Handleradapter is successfully obtained, the Interceptor Prehandler (...) will start executing. method). The
extracts the model data from the request, populates the handler entry, and begins the execution of the handler (Controller). In the process of populating the handler, depending on your configuration, Spring will do some extra work for you:
Httpmessageconveter: Converts the request message (such as Json, XML, and so on) to an object, converting the object to the specified response information.
Data Transformation: Data conversion for a request message. such as string conversion to Integer, double, and so on.
Data is initialized: Data is formatted for the request message. such as converting a string into a formatted number or a formatted date.
Data validation: Verifies the validity of the data (length, format, and so on), and the validation results are stored in Bindingresult or error. After the
Handler (Controller) executes, returns a Modelandview object to Dispatcherservlet;
based on the returned Modelandview, select a suitable The Viewresolver (must be a viewresolver already registered in the Spring container) is returned to Dispatcherservlet. The
Viewresolver combines model and view to render the view. The
view is responsible for returning the render results to the client.
7.3. Introduce Webapplicationcontext

Webapplicationcontext is an extension of applicationcontext. It has some of the extra features required by the WEB application. It differs from ordinary applicationcontext in the ability to parse a topic and decide which servlet to associate with.

Frequently asked spring-related questions in the Java interview (55 answers included)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.