General issues

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

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 separate 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?

**Spring Core Container – This layer is basically 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

  • The Web – the Servlet

  • Web – Socket

  • Web – Portlet

AOP – This layer supports section-oriented programming

Instrumentation – This layer provides support for class detection and class loader implementation.

**Test ** – This layer provides support for testing using JUnit and TestNG.

Several miscellaneous modules:

  • Messaging – This module supports STOMP. It also supports an annotation programming model, which is used to route and process STOMP messages from WebSocket clients

  • Aspects – This module supports integration with AspectJ.

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.

2.2. What is dependency injection?

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.

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
Internationalization is not supported Support internationalization
Dependency based annotations are not supported Support for 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.

Example:

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(); }}}Copy the code

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:

<bean id="studentbean" class="org.edureka.firstSpring.StudentBean">
 <property name="name" value="Edureka"></property>
</bean>
Copy the code
  • 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. Such as:

<beans> <context:annotation-config/> <! -- bean definitions go here --> </beans>Copy the code
  • Java API-based configuration

Spring’s Java Configuration is implemented using @Beans and @Configuration.

  1. The @bean annotation plays the same role as the element.

  2. 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() {
        returnnew StudentBean(); }}Copy the code

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. More on Spring

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

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

  1. The Spring container instantiates beans from the bean definition in the configuration

  2. Spring uses dependency injection to populate all properties, as defined in the bean configuration.

  3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() by passing in the bean’s ID.

  4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory() by passing an instance of itself.

  5. If there is any BeanPostProcessors associated with bean, call the preProcessBeforeInitialization () method.

  6. If the init method (of the init-method property) is specified for the bean, it will be called.

  7. Finally, if there is any BeanPostProcessors associated with bean, will call postProcessAfterInitialization () method.

  8. If the bean implements the DisposableBean interface, destory() will be called when the Spring container closes.

  9. 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
}
Copy the code

bean.xml

The < bean id = "StudentBean" class="com.edureka.Student"> person"> <! --This is inner bean --> <bean class="com.edureka.Person"> name"Value =" Scott"></property>
            <property name="address"Value = "Bangalore">   Copy the code

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 important Spring annotations have you used?

  • Controller – The Controller class used in the Spring MVC project.

  • @service – For Service classes.

  • @requestMapping – Used to configure URI mapping in controller handler methods.

  • ResponseBody – Used to send an Object as a response, usually to send XML or JSON data as a response.

  • @pathVariable – Used to map dynamic values from URIs to handler method parameters.

  • Autowired – Used to automatically assemble dependencies in Spring beans.

  • @Qualifier – Use the @AutoWired annotation to avoid confusion when there are multiple instances of the bean type.

  • @scope – Used to configure the Scope of the Spring bean.

  • @Configuration, @ComponentScan, and @Bean – for Java-based Configuration.

  • @aspect, @before, @after, @around, @pointcut – for Aspect programming (AOP).

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() {returnname; }}Copy the code

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() {returnname; }}Copy the 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 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.

public class Employee {
    private String name;
    @Autowired
    public void setName(String name) {
        this.name=name;
    }
    public string getName() {
        returnname; }}Copy the code

EmpAccount.java

public class EmpAccount {
    private Employee emp;

    @Autowired
    @Qualifier(emp1)
    public void showName() {system.out.println (" Employee name: "+emp.getName); }}Copy the code

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 can be applied at two levels:

  • Class level: URL of the mapping request

  • Method level: mapping URLS and HTTP request methods

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:

  1. Use Hibernate templates and callbacks for inversion of control

  2. Extend Hibernateda Support and apply the AOP interceptor node

5.5. List the transaction management types supported by Spring

Spring supports two types of transaction management:

  1. 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.

  2. 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 are the aspects, Advice, Pointcut, JointPoint, and Advice parameters in AOP?

  1. Aspect-aspect is a class that implements intersecting problems, such as transaction management. The Aspect can be a plain class configured and then configured in the Spring Bean configuration file, or we can declare the class as an Aspect using the @Aspect annotation supported by Spring AspectJ.

  2. Advice – Advice is the action taken for a specific JoinPoint. Programmatically, they are methods that are executed when a specific JoinPoint with a matching pointcut is reached in an application. You can think of Advice as a Spring Interceptor or a Servlet filter.

  3. Advice Arguments – We can pass Arguments in Advice methods. We can use the args() expression in the pointcut to apply to any method that matches the parameter pattern. If we use it, then we need to use the same name in the advice method that determines the parameter type.

  4. Pointcut – Pointcut is a regular expression that matches JoinPoint and is used to determine whether Advice needs to be performed. Pointcut uses a different type of expression that matches JoinPoint. The Spring framework uses the AspectJ Pointcut expression language to determine the JoinPoint to which the notification method will be applied.

  5. JoinPoint – JoinPoint is a specific point in an application, such as method execution, exception handling, changing object variable values, etc. In Spring AOP, JoinPoint is always the executor of a method.

6.3. 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.4. 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.

6.5. Show the difference between Concern and cross-cutting concern in Spring AOP

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.6. 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 load-time weaving (special class loader 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?

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.8. 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
Copy the code

6.9. 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, the MVC

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. Send an HTTP request to the server, which is captured by the front-end controller DispatcherServlet.

  2. DispatcherServlet parses the requested URL according to the configuration in -servlet.xml to obtain the request 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. The DispatcherServlet selects an appropriate HandlerAdapter based on the Handler obtained. (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, populate the Handler entry parameter, and start Handler (Controller). Depending on your configuration, Spring will do some extra work for you during the entry process to populate the Handler:

  • HttpMessageConveter: Converts the request message (such as Json or XML data) into an object, which is converted 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 DispatcherServlet after execution;

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

7.ViewResolver combines Model and View to render the View.

8. 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 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.