The Spring Framework is now almost the standard Framework for Java Web development. So, as a Java programmer, how much do you know about the main technical points of Spring? Use the questions in this article to test it.

1. General questions

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

Version Feature Spring 2.5 was released in 2007. This is the first version to support annotations. Spring 3.0 was released in 2009. It fully leverages improvements in Java5 and provides support for JEE6. Spring 4.0 was released in 2013. This is the first release to fully support JAVA8.

1.2. What is 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 J2EE application development. It can integrate other frameworks, such as Structs, Hibernate, EJB, etc., so it is also called the framework of frameworks.

1.3. List the advantages of the Spring Framework.

Due to the layered architecture of Spring Frameworks, users are free to choose which components they want. The Spring Framework supports POJOs (Plain Old Java Object) programming for continuous integration and testability. JDBC is simplified thanks to dependency injection and inversion of control. It’s open source and free.

1.4. What are the different features of the Spring Framework?

Lightweight – Spring is lightweight in terms of code volume and transparency. IOC – Inversion of Control AOP – Section-oriented programming can decouple application business logic from system services for high cohesion. Container-spring is responsible for creating and managing the life cycle and configuration of objects (beans). MVC – provides a high degree of configurability for Web applications and easy integration with other frameworks. Transaction Management – Provides a common abstraction layer for transaction management. Spring’s transaction support can also be used in environments with fewer containers. JDBC Exceptions – 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?

1.6. What is a Spring configuration file?

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

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

Spring applications typically have the following components:

Interface – Defines functions. Bean class – it contains properties, setter and getter methods, functions, and so on. Spring Tangential Programming (AOP) – Provides tangential programming capabilities. 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?

Spring can be used in the following ways:

As a full-fledged Spring Web application. As a third-party Web framework, use the Spring Frameworks middle layer. For remote use. As an enterprise-class Java Bean, it can wrap existing POJOs (Plain Old Java Objects).

2. Dependency Injection (Ioc)

2.1. What is the Spring IOC container?

At the heart of the Spring framework is the Spring container. Containers create objects, assemble them together, configure them, and manage their full life cycle. The Spring container uses dependency injection to manage the components that make up an application. The container receives instructions for instantiating, configuring, and assembling objects by reading the provided configuration metadata. This metadata can be provided through XML, Java annotations, or Java code.

In dependency injection, you don’t have to create objects, but you must describe how to create them. Rather than wiring components and services together directly in code, you describe which components in the configuration file require which services. The IoC container assembles them together.

2.3. How many ways can dependency injection be accomplished?

In general, dependency injection can be done in one of three ways:

Constructor injection Setter injection interface injection

In the Spring Framework, only constructors and setter injection are used.

2.4. Distinguish constructor injection from setter injection.

Constructor injection, setter injection, no partial injection, no partial injection, no override setter properties, no override setter properties, any change you make, you create a new instance, any change you make, you don’t create a new instance is good for setting a lot of properties and good for setting a few properties

2.5. How many IOC containers are available in Spring?

BeanFactory – BeanFactory is like a factory class that contains a collection of beans. It instantiates the bean when requested by the client. ApplicationContext – The ApplicationContext interface extends the BeanFactory interface. It provides some additional functionality on top of the BeanFactory.

2.6. Distinguish between BeanFactory and ApplicationContext.

BeanFactory ApplicationContext it uses lazy loading it uses instant loading it makes the terminology explicitly provide resource objects it creates and manages resource objects itself it doesn’t support internationalization it doesn’t support dependency based annotations it doesn’t support dependency based annotations

2.7. List some benefits of IoC.

Some of the benefits of IoC are:

It minimizes the amount of code in your application. It will make your application easy to test because it does not require any singletons or JNDI lookups in a unit test case. It promotes loose coupling with minimal impact and minimal intrusion mechanisms. It supports instant instantiation and lazy loading of services.

2.8. Implementation mechanism of Spring IoC.

The implementation principle of IoC in Spring is factory mode plus reflection mechanism.

Interface Fruit {public abstract void eat(); } class Apple implements Fruit { public void eat(){ System.out.println(“Apple”); } } class Orange implements Fruit { public void eat(){ System.out.println(“Orange”); } } class Factory { public static Fruit getInstance(String ClassName) { Fruit f=null; try { f=(Fruit)Class.forName(ClassName).newInstance(); } catch (Exception e) { e.printStackTrace(); } return f; } } class Client { public static void main(String[] a) { Fruit f=Factory.getInstance(“io.github.dunwu.spring.Apple”); if(f! =null){ f.eat(); } } } 3. Beans

3.1. What are Spring beans?

They are the objects that form the backbone of a user’s 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 configuration metadata provided by the user to the container.

3.2. What configuration methods does Spring provide?

Xml-based Configuration

The dependencies and services required by the bean are specified in an XML-formatted configuration file. These configuration files typically contain many bean definitions and application-specific configuration options. They usually start with a bean label. Such as:

Annotation-based configuration

Instead of using XML to describe bean assembly, you can configure beans as component classes themselves by using annotations on the associated class, method, or field declarations. By default, the annotation assembly is not open in the Spring container. Therefore, you need to enable it in your Spring configuration file before using it. For example: context: the annotation – config /

3.3. Spring supports centralized bean scopes?

Spring beans support five scopes:

Singleton – Only one single instance per Spring IoC container. Prototype – Each request generates a new instance. Request – Each HTTP Request generates a new instance, and the bean is only valid within the current HTTP Request. Session – Each HTTP request generates a new bean that is valid only for the current HTTP Session. Global-session – is similar to the standard HTTP session scope, but only makes sense in portlet-based Web applications. The Portlet specification defines the concept of a global Session, which is shared by all the different portlets that make up a Portlet Web application. Beans defined in the Global Session scope are limited to the lifecycle of the global Portlet session. If you use the Global Session scope on the Web to identify beans, the Web will automatically use it as a session type.

The last three are available only if the user uses a Web-enabled ApplicationContext.

3.4. What is the lifecycle of the Spring Bean container?

The lifecycle flow of the Spring Bean container is as follows:

The Spring container instantiates beans from the bean definition in the configuration. Spring uses dependency injection to populate all properties, as defined in the bean configuration. If the bean implements the BeanNameAware interface, the factory calls setBeanName() by passing in the bean’s ID. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory() by passing an instance of itself. If there is any BeanPostProcessors associated with bean, call the preProcessBeforeInitialization () method. If the init method (of the init-method property) is specified for the bean, it will be called. Finally, if there is any BeanPostProcessors associated with bean, will call postProcessAfterInitialization () method. If the bean implements the DisposableBean interface, destory() will be called when the Spring container closes. If the destroy method (with the destroy-method attribute) is specified for the bean, it will be called.

3.5. What are Spring’s internal beans?

A bean can only be declared as an internal bean if it is used as a property of another bean. To define beans, Spring’s XML-based configuration metadata provides the use of elements in or. Inner beans are always anonymous; they are always 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 name; private String address; //Setters and Getters }

bean.xml

<bean id= “StudentBean” class=”com.edu reka-student “> <property name=”name” value=” Scott”> <property name=”address” Value = “Bangalore” >

3.6. What is Spring assembly

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

3.7. What are the methods of automatic assembly?

The Spring container can automatically assemble beans. That is, Spring can automatically resolve the bean’s collaborators by examining the contents of the BeanFactory.

Different modes of automatic assembly:

No – This is the default setting, indicating no autowiring. Assembly should be done using explicit bean references. ByName – It injects object dependencies based on the bean name. It matches and assembles its attributes with beans defined by the same name in the XML file. ByType – It injects object dependencies based on type. If the type of the attribute matches a bean name in the XML file, the attribute is matched and assembled. Constructor – It injects dependencies by calling the constructor of the class. It has a lot of parameters. Autodetect – First the container tries to assemble using Autowire via constructors, and if not, tries byType autoassembly.

3.8. What are the limitations of autowiring?

Possibility of override – You can always use and set specified dependencies that will override autowiring. Basic metadata types – Simple properties (such as primitive data types, strings, and classes) cannot be assembled automatically. Confusing nature – always prefer to use explicit assembly because autoassembly is not very accurate.

4, annotations,

4.1. What is annotation-based container configuration

Instead of using XML to describe bean assembly, the developer moves the configuration to the component class itself by using annotations on the associated class, method, or field declarations. It can be used as an alternative to XML Settings. For example, Spring’s Java Configuration is implemented using @Bean and @Configuration.

The @bean annotation plays the same role as the element. The @Configuration class allows you to define inter-bean dependencies by simply calling other @Bean methods in the same class.

Such as:

@Configuration public class StudentConfig { @Bean public StudentBean myStudent() { return new StudentBean(); }}

4.2. How do I start annotation assembly in Spring?

By default, the annotation 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. What is the difference between @Component, @Controller, @Repository and @service?

@Component: This marks the Java class as a bean. It is a common stereotype for any Spring management component. Spring’s component scanning mechanism can now pick them up and pull them into the application environment. Controller: This marks a class as a Spring Web MVC Controller. Beans labeled with it are automatically imported into the IoC container. @service: This annotation is a specialization of the component annotation. It does not provide any additional behavior for the @Component annotation. You can use @Service instead of @Component in the Service layer class because it specifies intents in a better way. @Repository: This annotation is a specialization of the @Component annotation with similar utility and functionality. It provides additional benefits for daOs. It imports the DAO into the IoC container and makes unchecked exceptions eligible for translation into Spring DataAccessException.

4.4. What is the use of the @required annotation?

@required applies to the bean property setter method. This annotation merely indicates that the explicit property values in the bean definition must be used at configuration time or the affected bean properties must be populated with autoassembly. If it is not already filled the bean properties affected, the container will throw BeanInitializationException. Example:

public class Employee { private String name; @Required public void setName(String name){ this.name=name; } public string getName(){ return name; }}

4.5. What is the use of @autowired annotations?

@autoWired gives you more control over where and how autoassembly should take place. This annotation is used to automatically assemble beans on setter methods, constructors, properties or methods with arbitrary names 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; }}

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 them using properties, you can use the @Qualifier annotation and @AutoWired to disambiguously specify which exact bean should be assembled.

For example, here we have two classes, Employee and EmpAccount. In EmpAccount, the @Qualifier is used to specify 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() {system.out.println (” Employee name: “+emp.getName); }}

4.7. What is the @requestMapping annotation for?

The @RequestMapping annotation is used to map a specific HTTP request method to a specific class/method in the controller that will handle the corresponding request. This annotation applies at two levels:

Class level: mapping request URL method level: mapping URL and HTTP request method

5. Data access

5.1. What is the Use of spring DAO?

The Spring DAO makes it easier for data access technologies like JDBC, Hibernate, or JDO to work in a unified way. This makes it easy for users to switch between persistence technologies. It also allows you to write code without having to worry about catching exceptions that are different for each technology.

5.2. List exceptions thrown by the Spring DAO.

5.3. What classes exist in the Spring JDBC API?

JdbcTemplate SimpleJdbcTemplate NamedParameterJdbcTemplate SimpleJdbcInsert SimpleJdbcCall

5.4. What are the ways to access Hibernate using Spring?

We can use Spring to access Hibernate in two ways:

Extend inversion of control to Hibernateda Support using Hibernate templates and callbacks and apply AOP interceptor nodes

5.5. List the transaction management types supported by Spring

Spring supports two types of transaction management:

Programmatic transaction management: In this process, transactions are managed with the help of programming. It gives you great flexibility, but is very difficult to maintain. Declarative transaction management: Here, transaction management is separated from the business code. Use only annotations or XML-based configurations to manage transactions.

5.6. Which ORM frameworks spring supports

Hibernate iBatis JPA JDO OJB

6, AOP

6.1. What is AOP?

AOP(aspect-oriented Programming), namely Aspect Oriented Programming, is complementary to OOP(Object-oriented Programming) and provides a different perspective of abstract software structure from OOP.

In OOP, we use classes as our base unit, whereas in AOP, the base unit is aspects

6.2. What is Aspect?

An aspect consists of pointcount and advice, and contains both the definition of crosscutting logic and the definition of join points. Spring AOP is the framework responsible for implementing the aspect, weaving the crosscutting logic defined by the aspect into the join points specified by the aspect.

AOP’s focus is on how to enhance the join points of the woven target objects, which consists of two tasks:

How to locate a specific JoinPoint via PointCut and Advice How to write aspect code in Advice

It is easy to think of a class annotated with @aspect as an Aspect.

Some point in a program’s execution, such as the execution of a method or the handling of an exception. In Spring AOP, a Join point is always the execution point of a method.

6.4. What is Advice?

The action taken by the Aspect at a particular JoinPoint is called Advice. Spring AOP maintains a series of interceptors “around” JoinPoint using an Advice as an interceptor.

6.5. What types of Advice are available?

Before – These types of Advice are executed Before the JoinPoint method and configured using the @before annotation tag. AfterReturning – These types of Advice are executed After normal execution of join point methods and are configured using the @AfterRETURNING annotation flag. AfterThrowing – These types of Advice are only performed when the JoinPoint method exits by Throwing an exception and is configured using the @AfterThrowing annotation tag. After (finally) – These types of Advice are executed After the join point method, whether the method exit returns normally or abnormally, and are configured using the @After annotation flag. Around – These types of Advice are executed before and after join points and are configured using the @around annotation tag.

In Spring AOP, concern is different from cross-cutting concern.

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

Cross-cutting Concern is an application-wide behavior that affects the entire application. For example, logging, security, and data transfer are issues that need to be addressed by almost every module of the application, so they are cross-domain issues.

6.7. What are the implementations of AOP?

The technologies for implementing AOP fall into two main categories:

Static proxy – refers to compilation using commands provided by the AOP framework so that AOP proxy classes can be generated at compile time, hence also called compile-time enhancement; Compile-time weaving (special compiler implementation) class-time weaving (special classloader implementation). Dynamic proxy – Generates AOP dynamic proxy classes “temporarily” in memory at run time and is therefore also known as runtime enhancement. JDK dynamic proxy CGLIB

What is the difference between Spring AOP and AspectJ AOP?

Spring AOP is implemented based on dynamic proxy; AspectJ is implemented using static proxies. Spring AOP supports only method-level pointcuts; Full AOP support is provided, and it also supports property-level pointcuts.

6.9. How to understand proxies in Spring?

The objects created after Advice is applied to the target object are called proxies. In the case of the client object, the target object and the proxy object are identical.

Advice + Target Object = Proxy

What is Weaving?

Weaving links an aspect to other application types or objects in order to create an advice object. In Spring AOP, weaving is performed at run time. Please refer to the picture below:

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

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

7.2. Describe the workflow of the DispatcherServlet

The workflow of the DispatcherServlet can be illustrated with a diagram:

1 Sends an HTTP request to the server. The request is captured by the front-end controller DispatcherServlet. DispatcherServlet addresses the requested URL according to the configuration in -servlet.xml

2 Parses and obtains the requested resource identifier (URI). Then, based on the URI, HandlerMapping is called to retrieve all relevant objects (including Handler objects and interceptors corresponding to Handler objects) configured by this Handler, which are returned as HandlerExecutionChain objects.

3 DispatcherServlet Selects an appropriate HandlerAdapter based on the obtained Handler. (Note: If the HandlerAdapter is successfully obtained, execution of the interceptor’s preHandler(…) begins at this point.) Methods).

4 Extract the model data from the Request, fill in the Handler input parameter, and run Handler (Controller). Depending on your configuration, Spring does some extra work for you during the entry process of populating the Handler: HttpMessageConveter: Converts the request message (such as Json, XML, etc.) into an object, which converts the object into the specified response information. Data transformation: Data transformation of the request message. Such as String to Integer, Double, and so on. Data root: Data formatting of the request message. For example, converting a string to a formatted number or a formatted date. Data validation: Verifies the validity of data (length, format, etc.) and stores the validation results in BindingResult or Error.

5 Handler(Controller) Returns a ModelAndView object to the DispatcherServlet.

6 According to the returned ModelAndView, select a suitable ViewResolver (the ViewResolver must be registered in the Spring container) to return to the DispatcherServlet.

ViewResolver combines Model and View to render the View.

The view is responsible for returning the rendered results to the client.

7.3. Introduce WebApplicationContext

WebApplicationContext is an extension of ApplicationContext. It has some additional functionality required for Web applications. It differs from a normal ApplicationContext in its ability to resolve topics and decide which servlet to associate with.