An alternative to XML setups, annotation-based container configuration, is used to describe a bean wiring. The developer transfers the configuration into the component class by using annotations on the method, class, or field declaration.
Even though both allow you to reduce coupling in code, dependency injection is much more flexible and easier to test than Factory pattern
This one is a very popular Spring interview question and often asks in an entry-level interview. ApplicationContext is the preferred way of using spring because of the functionality provided by it and the interviewer wanted to check whether you are familiar with it or not.
Advice will tell application on new behavior and it is the implementation of an aspect. It is inserted into an application at the joinpoint.
Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, the advice is inserted into an application at joinpoints.
When only a small amount of transactional operations is there, it is advised to use Programmatic transaction management. But if there is a big amount of transactional operations to be taken care of, declarative transaction management is preferred.
Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret
user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very
abstract way, which enables you to create a wide variety of controllers.
Weaving is the process of linking aspects with other application types or objects to create an advised object. Weaving can be
done at compile time, at load time, or at runtime.
The target object is an object being advised by one or more aspects. It will always be a proxy object. It is also referred to as the
advised object.
• It provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
• It provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
• It supports declarative transaction management.
• It integrates very well with Spring’s various data access abstractions.
Use Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps:
• Configure the Hibernate SessionFactory
• Extend a DAO Implementation from HibernateDaoSupport
• Wire in Transaction Support with AOP
When using the Spring JDBC framework the burden of resource management and error handling is reduced. So developers only
need to write the statements and queries to get the data to and from the database. JDBC can be used more efficiently with the
help of a template class provided by Spring framework, which is the JdbcTemplate
An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for wiring
up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the
configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
Limitations of autowiring are:
• Overriding: You can still specify dependencies using <constructor-arg> and <property> settings which will always
override autowiring.
• Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes.
• Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.
With the JDBC abstraction and DAO module we can be sure that we keep up the database code clean and simple, and prevent
problems that result from a failure to close database resources. It provides a layer of meaningful exceptions on top of the error
messages given by several database servers. It also makes use of Spring’s AOP module to provide transaction management
services for objects in a Spring application.
This is the basic Spring module, which provides the fundamental functionality of the Spring framework. BeanFactory is the
heart of any spring-based application. Spring framework was built on the top of this module, which makes the Spring container.
There are a couple of limitations/restrictions one faces using auto wiring like:
Overriding possibility: By using the <constructor-arg> and <property> settings, you can specify dependencies. It will override auto wiring.
Primitive data type: Primitive data type, classes, and strings cannot be auto wired.
Declarative transaction management: This type manages transactions using annotations or XML configurations to separate transaction management from the program’s business code. While easy to maintain, this style is more restricted in its capabilities.
Programmatic transaction management: This type manages transactions with specifically made programs. The customization of these programs allows for more flexible management but introduces more room for error in the process.
Boot allows both in the same application but can only apply one at a time. WebFlux is a non-blocking framework while MVC is a blocking framework, making them incompatible together.
The WebClient is a component from the Web Reactive framework that makes it easier to build reactive and non-blocking web applications.
The Webtestclient is a version of this client with all the same features but is disconnected from live environments. The test client doesn’t need an HTTP server live environment to work, making it a good test environment for new applications. It can connect to any server over an HTTP connection or sync directly with WebFlux to apply mock HTTP requests and generate response objects.
Reactive Programming is a programming paradigm that relies on programmed actions trigger on events rather than based on the chronological order of the code. Reactive programs make efficient use of computer resources and scale well with just a few threads. Its non-sequential form allows you to avoid stack blocking and maintain responsiveness.
Following are the different types of events of listeners:
1. ContextClosedEvent – This event is called when the context is closed.
2. ContextRefreshedEvent – This event is called when context is initialized or refreshed
3. RequestHandledEvent – This event is called when the web context handles request
It is basically an XML file. You can find all the information about the classes in this file. It further describes how these classes are configured and known to each other. The XML configuration files are detailed, so it is necessary to keep them clean. Otherwise, managing them becomes difficult if your project is big.
There are two ways to do dependency injection in Spring.
Dependency injection via setter method
Dependency injection via the constructor.
The 3 main parts of MVC are:
DispatcherServlet: This part of MVC manages all the HTTP requests, and responses that interact with the program. The DispatcherServlet first receives relevant handler mapping from the configuration file and then passes off the request to the controller. The DispatcherServlet is the most important part of the Spring Web MVC framework.
WebApplicationContext: This acts as an extension of the plain ApplicationContext with extra features necessary for web applications. It can uniquely resolve themes and automatically decide which servlet it is associated with.
Controllers: These are beans within the DispatcherServlet that act as filters between user input and application response. Controllers take user input, decide if it should be transformed into either a View or a Model, and finally returns the transformed input to the View Resolver for review.
You can have more than one bean of the same type in your XML configuration but you want to autowire only one of them, so @Qualifier removes confusion created by @Autowired by declaring exactly which bean is to autowired.
Describe them briefly.
Core – a key module that provides fundamental parts of the framework, like IoC or DI
JDBC – this module enables a JDBC-abstraction layer that removes the need to do JDBC coding for specific vendor databases
ORM integration – provides integration layers for popular object-relational mapping APIs, such as JPA, JDO, and Hibernate
Web – a web-oriented integration module, providing multipart file upload, Servlet listeners, and web-oriented application context functionalities
MVC framework – a web module implementing the Model View Controller design pattern
AOP module – aspect-oriented programming implementation allowing the definition of clean method-interceptors and pointcuts.
Spring targets to make Java EE development easier. Here are the advantages of using it:
Lightweight: there is a slight overhead of using the framework in development
Inversion of Control (IoC): Spring container takes care of wiring dependencies of various objects, instead of creating or looking for dependent objects
Aspect Oriented Programming (AOP): Spring supports AOP to separate business logic from system services
IoC container: it manages Spring Bean life cycle and project specific configurations
MVC framework: that is used to create web applications or RESTful web services, capable of returning XML/JSON responses
Transaction management: reduces the amount of boiler-plate code in JDBC operations, file uploading, etc., either by using Java annotations or by Spring Bean XML configuration file
Exception Handling: Spring provides a convenient API for translating technology-specific exceptions into unchecked exceptions. (E Learning Portal)
The concern can be defined as a functionality/feature a programmer wants to implement to address a specific business problem. For example, In eCommerce applications a concern can be stock management, shipping management etc.
Crosscutting concern is a concern than span across almost all modules of an application. For example, logging, security etc.
Autoproxying is used to create proxy automatically for the spring users. It provides following two classes to support this automatic proxy creation. There are different types of AutoProxying. They are
1.BeanNameAutoProxyCreator
2.DefaultAdvisorAutoProxyCreator
3.MetadataAutoProxying
Spring batch is mainly used to read & write files, and also in performing certain operations in the database like reading or writing, data transformation, report creation, also import and export data, etc
Spring supports ORM like Hibernate, IBatis, TopLink, Java Data Object, OJB, and JPA, etc.
Since the field is constantly changing, it is of course important to keep up one’s knowledge. For this purpose, I do a couple of things. For one, I make sure to take continuing education classes. I also try to read up on books and magazines. Then of course there are conferences — I try and go to at least one or two a year, since they can be so educational.
The interviewer wants to makes sure that you’re willing to maintain your expertise.
Dispatcher Servlet is used to handle all the incoming HTTP requests and responses from the client. Overall, it controls all the communications from the handler to the controller to view the resolver to the actual view page.
Declarative Transaction Management is widely used by developers.
Transaction is basically some operation performed on some data in the database. Transaction Management comes under the Relational Database management system and is used to ensure data ethics and consistency.
The core advantage of Transaction Management is that it supports declarative and programmatic Transaction Management and APIs like Hibernate, JTA, and JDBC by correct integration.
It is mainly used when the developer is bound to create many beans of the same type and want to wire only one of them with the property, in this scenario @Qualifier with @Autowired is used for removing confusion and specifying the exact bean to be wired.
It is used to indicate that at configuration time, the bean property should be populated through autowiring or explicit property value in the bean definition.
Example:
package com.softwaretestinghelp;
import org.Springframework.beans.factory.annotation.Required;
public class Employee {
private Integer age;
private String Lname;
@Required
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
@Required
public void setLName(String Lname) {
this.name = name;
}
public String getLName() {
return name;
}
}
Yes, there are some limitations of autowiring which are as mentioned below:
There is always a possibility of overriding.
The developer will not be able to autowire primitive and Spring properties.
Autowiring becomes complex when used in big applications compared to explicit wiring.
Basically, there are four collection elements to insert in Spring.
They are:
<set> element – It wires the set of values by eliminating the duplicates from them.
<list> element – It is useful to insert or inject values and also allows duplicate values.
<map> element – It is used to insert a key or name-value pair which can be of any type.
<props> element – It is used to insert key or name-value pairs, but the type should only be the string.
Basically, bean definition holds the configuration metadata that is used by the Spring container to know details like, bean creation process, the life cycle of bean and dependencies of a bean.
AOP stands for Aspect Oriented Programming. It is another approach of programming that helps the developers to restructure the behavior of responsibilities like Transaction Management and logging.
AOP is implemented for cross-cutting concerns, i.e. the definition is provided in one place and functionally it can be used in many places with the help of the script.
The five main modules in Spring Framework are mentioned below:
1.Spring Core Container which includes core, beans, context, and expression language.
2.AOP and Aspects.
3.Data Integration Module which includes JDBC, OXM, ORM, transaction modules etc.
4.Web Module that includes web, servlet, struts, and portlet.
5.Test
The BeanFactory is a basic, space-efficient container with limited functionality. It is best used for simple tasks or when using low-resource machines.
The ApplicationContext is an advanced, more intensive container with an extended interface and additional capabilities like AOP. This container is best used when you need more functionality than the BeanFactory and have ample resources available on the machine.
Dependency injection (DI) is a concept that defines how multiple classes should be connected. This is one example of Inversion of Control. You don’t need to connect services and components explicitly in code when using dependency injection. Instead, you describe the services needed by each component in an XML configuration file and allow the IOC container to connect them automatically.
This is a “gotcha†question used to test if you know how different object types interact. The target and proxy objects are the same when dealing with client objects.
Dependency injection (DI) is a concept that defines how multiple classes should be connected. This is one example of Inversion of Control. You don’t need to connect services and components explicitly in code when using dependency injection. Instead, you describe the services needed by each component in an XML configuration file and allow the IOC container to connect them automatically.
JDBC can be used more efficiently with the help of a template class provided by spring framework called as JdbcTemplate.
Spring offers four types of collection configuration elements which are as follows −
<list> − This helps in wiring i.e. injecting a list of values, allowing duplicates.
<set> − This helps in wiring a set of values but without any duplicates.
<map> − This can be used to inject a collection of name-value pairs where name and value can be of any type.
<props> − This can be used to inject a collection of name-value pairs where the name and value are both Strings.
This is the basic Spring module, which provides the fundamental functionality of the Spring framework. BeanFactory is the heart of any spring-based application. Spring framework was built on the top of this module, which makes the Spring containe
There are around 20 modules in total and are divided into the layers of Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, and Test.
Core Container: The core of the Spring Framework contains 4 modules.
1. Spring Core
2. Spring Bean
3. SpEL (Spring Expression Language)
4. Spring Context
Data Access/Integration: Supports database interactions with 5 modules.
1. JDBC (Java DataBase Connectivity)
2. ORM (Object Relational Mapping)
3. OXM (Object XML Mappers)
4. JMS (Java Messaging Service)
5. Transaction
Aspect-Oriented Programming: This layer allows you to decouple code using Advice and Pointcut functions.
Instrumentation: This layer adds support for class instrumentation and classloader implementations.
Test: Adds support for testing using Junit and TestNG.