Google News
logo
Java Springs Interview Questions
Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.
* Spring framework follows layered architecture pattern that helps in the necessary components selection along with providing a robust and cohesive framework for J2EE applications development.

* The AOP (Aspect Oriented Programming) part of Spring supports unified development by ensuring separation of application’s business logic from other system services.

* Spring provides highly configurable MVC web application framework which has the ability to switch to other frameworks easily.

* Provides provision of creation and management of the configurations and defining the lifecycle of application objects.

* Spring has a special design principle which is known as IoC (Inversion of Control) that supports objects to give their dependencies rather than looking for creating dependent objects.

* Spring is a lightweight, java based, loosely coupled framework.

* Spring provides generic abstraction layer for transaction management that is also very useful for container-less environments.

* Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate or other frameworks) into consistent, unchecked exceptions. This introduces abstraction and greatly simplifies exception handling.
Spring AOP : One of the key components of Spring is the AOP framework. AOP is used in Spring:
* To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on Spring’s transaction abstraction.
* To allow users to implement custom aspects, complementing their use of OOP with AOP
* Spring ORM : The ORM package is related to the database access. It provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis.
* Spring Web : The Spring Web module is part of Spring?s web application development stack, which includes Spring MVC.
* Spring DAO : The DAO (Data Access Object) support in Spring is primarily for standardizing the data access work using the technologies like JDBC, Hibernate or JDO.
* Spring Context : This package builds on the beans package to add support for message sources and for the Observer design pattern, and the ability for application objects to obtain resources using a consistent API.
* Spring Web MVC : This is the Module which provides the MVC implementations for the web applications.
* Spring Core : The Core package is the most import component of the Spring Framework.
This component provides the Dependency Injection features. The BeanFactory  provides a factory pattern which separates the dependencies like initialization, creation and access of the objects from your actual program logic.
In software engineering, Inversion of Control (IoC) is a programming technique in which object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis.
 
In traditional programming, the business logic flow is determined by objects statically assigned to one another.
 
With inversion of control, the application flow depends on the object graph instantiated by the assembler and is made possible by object interactions defined through abstractions. The binding process is achieved through “dependency injection“.
 
Inversion of control is a design paradigm to give more control to the targeted components of the application, the ones that are actually doing the work.
 
Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality.
 
Inversion of control relies on dependency injection because a mechanism is needed to activate the components providing the specific functionality. Otherwise, how will the framework know which components to create if it is no longer in control?
 
In Spring, dependency injection may happen in the following ways :
 
* Constructor injection
* Setter injection
* Fields Injection
A typical Spring application can be subdivided into the following components :
 
Bean Class : Contains properties, functions, setter and getter methods, et cetera
Bean Configuration File : Contains information on classes as well as how to configure the same
Interface : Defines the functions
Spring Aspect Oriented Programming : Provides the functionality of cross-cutting concerns
User Program : Uses the function
Annotation Based Dependency : BeanFactory doesn’t support annotation-based dependency while ApplicationContext does
Interface Definition : BeanFactory interface is defined in org.springframework.beans.factory.BeanFactory while the ApplicationContext interface is defined in org.springframework.context.ApplicationContext
Internationalization Support : While ApplicationContext supports internationalization, BeanFactory doesn’t
Object Management : BeanFactory uses syntax for providing a resource object. Contrarily, ApplicationContext creates as well as manages resource objects on its own
Type of Initialization : ApplicationContext makes use of eager or aggressive initialization. On the other hand, BeanFactory uses lazy initialization
* In the spring framework, inversion of control refers to the framework’s ability to create, destroy, and manage the beans’ lifecycle.
 
* The ApplicationContext (internally, it uses BeanFactory) is in the center of inversion of control in Spring.
 
* To assemble beans, the spring bean factory uses configuration metadata, which can be in the form of XML configuration or annotations.
we can configure Spring into our applications in 3 ways:
 
* XML based configuration
* Annotation-based configuration
* Java-based configuration
 
The most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application.
Spring 5 is a major overhaul from Spring 4. Some of the important features are :
 
* Support for Java 8 and higher versions, so we can use lambda expressions.
* Support for Java EE7 and Servlet 4.0 specs.
* File operations are performed via NIO 2 streams now, a huge improvement if your app does a lot of file handling.
* Introduction of spring-jcl to streamline logging, earlier it was a mess due to no single point for logging purposes.
* Support for Kotlin, Lombok, Reactor 3.1 Flux, and Mono as well as RxJava.
* Spring WebFlux that brings reactive programming to Spring.
* Support for JUnit 5
* Support for providing spring components information through index file “META-INF/spring.components” rather than classpath scanning.
Spring WebFlux is the new module introduced in Spring 5. Spring WebFlux is the first step towards the reactive programming model in the spring framework.
 
Spring WebFlux is the alternative to the Spring MVC module. Spring WebFlux is used to create a fully asynchronous and non-blocking application built on the event-loop execution model.
Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement the dependency injection pattern to move the dependency resolution from compile-time to runtime.
 
Some of the benefits of using Dependency Injection are Separation of Concerns, Boilerplate Code reduction, Configurable components, and easy unit testing.
We can install plugins into Eclipse to get all the features of Spring Tool Suite. However, STS comes with Eclipse with some other important kinds of stuff such as Maven support, Templates for creating different types of Spring projects, and tc server for better performance with Spring applications.
 
I like STS because it highlights the Spring components and if you are using AOP pointcuts and advice, then it clearly shows which methods will come under the specific pointcut. So rather than installing everything on our own, I prefer using STS when developing Spring-based applications.
Enterprise applications have some common cross-cutting concerns that are applicable to different types of Objects and application modules, such as logging, transaction management, data validation, authentication, etc. The modularity of application is achieved by classes in Object-oriented programming. In AOP, application modularity is achieved by Aspects and they are configured to cut across different class methods.
 
AOP takes out the direct dependency of cross-cutting tasks from classes that are not possible in normal object-oriented programming. For example, we can have a separate class for logging but the other classes will have to call these methods. But, in AOP we configure the aspects and method execution happens automatically.
Aspect : Aspect is a class that implements cross-cutting concerns, such as transaction management. Aspects can be a normal class configured and then configured in the Spring Bean configuration file or we can use Spring AspectJ support to declare a class as an Aspect using @Aspect annotation.
 
Advice : Advice is the action taken for a particular join point. In terms of programming, they are methods that get executed when a specific join point with a matching pointcut is reached in the application. You can think of Advice as Spring interceptors or Servlet Filters.
 
Pointcut : Pointcuts are regular expressions that are matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points. Spring framework uses the AspectJ pointcut expression language for determining the join points where advice methods will be applied.
 
JoinPoint : A join point is a specific point in the application such as method execution, exception handling, changing object variable values, etc. In Spring AOP a join point is always the execution of a method.
 
Advice Arguments : We can pass arguments in the advice methods. We can use the args() expression in the pointcut to be applied to any method that matches the argument pattern. If we use this, then we need to use the same name in the advice method from where the argument type is determined.
Syntax :
<? xml version ="1.0" encoding ="UTF-8"?>
<beansxmlns="HTTP://www.Springframework.org/schema/beans"xmlns:xsi="HTTP://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="HTTP://www.Springframework.org/schema/beans
HTTP://www.Springframework.org/schema/beans/Spring-beans.xsd">

<beanid="helloWorld"class="com.demoprogram.HelloWorld">
<propertyname="info"value="Hello World!"/>
</bean>
</beans>
Bean scope can be defined as singleton and prototype, request, session, global-session, etc.
 
* Prototype is declared when a new bean instance is required every time.
* Singleton is declared when the same bean instance is used every time.
* Request is used for the HTTP request scope.
* Session is used for the HTTP session scope.
* Global-HTTP session scopes the bean to the global HTTP session.

Syntax : <bean>
* In constructor injection, partial injection is not allowed whereas it is allowed in setter injection.
* The constructor injection doesn’t override the setter property whereas the same is not true for setter injection.
* Constructor injection creates a new instance if any modification is done. The creation of a new instance is not possible in setter injection.
* In case the bean has many properties, then constructor injection is preferred. If it has few properties, then setter injection is preferred.
There are 3 ways of providing the configuration metadata. They are as follows :
 
XML-Based configuration : The bean configurations and their dependencies are specified in XML configuration files. This starts with a bean tag as shown below :
<bean id="FreeTimeLearning" class="org.freetimelearn.firstSpring.FreeTimeLearning">
  <property name="name" value="freetimelearn"></property>
</bean>​

 

Annotation-Based configuration : Instead of the XML approach, the beans can be configured into the component class itself by using annotations on the relevant class, method, or field declaration.
Annotation wiring is not active in the Spring container by default. This has to be enabled in the Spring XML configuration file as shown below
<beans>
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>​
Java-based configuration : Spring Framework introduced key features as part of new Java configuration support. This makes use of the @Configuration annotated classes and @Bean annotated methods.

* @Bean annotation has the same role as the <bean/> element.
* Classes annotated with @Configuration allow to define inter-bean dependencies by simply calling other @Bean methods in the same class.
The Bean life cycle is as follows :
 
* The IoC container instantiates the bean from the bean’s definition in the XML file.
* Spring then populates all of the properties using the dependency injection as specified in the bean definition.
* The bean factory container calls setBeanName() which take the bean ID and the corresponding bean has to implement BeanNameAware interface.
* The factory then calls setBeanFactory() by passing an instance of itself (if BeanFactoryAware interface is implemented in the bean).
* If BeanPostProcessors is associated with a bean, then the preProcessBeforeInitialization() methods are invoked.
If an init-method is specified, then it will be called.
* Lastly, postProcessAfterInitialization() methods will be called if there are any BeanPostProcessors associated with the bean that needs to be run post creation.
The IoC container autowires relationships between the application beans. Spring lets collaborators resolve which bean has to be wired automatically by inspecting the contents of the BeanFactory.

Different modes of this process are :
 
* no : This means no autowiring and is the default setting. An explicit bean reference should be used for wiring.
* byName : The bean dependency is injected according to the name of the bean. This matches and wires its properties with the beans defined by the same names as per the configuration.
* byType : This injects the bean dependency based on type.
* constructor : Here, it injects the bean dependency by calling the constructor of the class. It has a large number of parameters.
* autodetect : First the container tries to wire using autowire by the constructor, if it isn't possible then it tries to autowire by byType.
Overriding possibility : Dependencies are specified using <constructor-arg> and <property>  settings that override autowiring.

Data types restriction : Primitive data types, Strings, and Classes can’t be autowired.
Spring Framework can be used in various ways. They are listed as follows :
 
* As a Full-fledged Spring web application.
* As a third-party web framework, using Spring Frameworks middle-tier.
* For remote usage. 
* As Enterprise Java Bean which can wrap existing POJOs (Plain Old Java Objects).
 
The next section of Spring Interview Questions is on Dependency Injection and IoC container.
In order to set Spring Bean's scope, we can use @Scope annotation or “scope” attribute in XML configuration files. Note that there are five supported scopes :
 
* Singleton
* Prototype
* Request
* Session
* Global-session
First, a Spring bean needs to be instantiated based on Java or XML bean definition. It may also be required to perform some initialization to get it into a usable state. After that, when the bean is no longer required, it will be removed from the IoC container.
Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.
 
To use Spring Security in web applications, we can get started with the simple annotation @EnableWebSecurity.
We can do either by implementing Spring-aware interfaces. The complete list is available here.
 
We could also use @Autowired annotation on those beans :
@Autowired
ServletContext servletContext;

@Autowired
ServletConfig servletConfig;
The @RequestMapping annotation is used to map web requests to Spring Controller methods. In addition to simple use cases, we can use it for mapping of HTTP headers, binding parts of the URI with @PathVariable, and working with URI parameters and the @RequestParam annotation.
Following is sequence of a bean lifecycle in Spring :
 
Instantiate : First the spring container finds the bean's definition from the XML file and instantiates the bean..
 
Populate properties : Using the dependency injection, spring populates all of the properties as specified in the bean definition.
 
Set Bean Name : If the bean implements BeanNameAware interface, spring passes the bean's id to setBeanName() method.
 
Set Bean factory : If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
 
Pre Initialization : Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
 
Initialize beans : If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
 
Post Initialization : If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
 
Ready to use : Now the bean is ready to use by the application.

Destroy : If the bean implements DisposableBean , it will call the destroy() method
A <bean/> element inside the <property/> or <constructor-arg/>  elements defines a so-called inner bean. An inner bean definition does not require a defined id or name; the container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are always scoped as prototypes.
<bean id = "outerBean" class = "...">
      <property name = "target">
         <bean id = "innerBean" class = "..."/>
      </property>
</bean>​
This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected bean property has not been populated.
This annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.
There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.
Spring has JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations.
 
@PostConstruct : This annotation can be used as an alternate of initialization callback.
 
@PreDestroy : This annotation can be used as an alternate of destruction callback.
 
@Resource : This annotation can be used on fields or setter methods. The @Resource annotation takes a 'name' attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics.
When you define a Bean to be injected in another class, Spring creates an object of the Bean which is managed by the Spring container ready for use.
 
If you decide to use constructor injection, create another Bean and reference to the previous object to be injected in this class.
 
For example, we can create an email service Bean, which will be injected into the customer to provide messaging services, as shown below.
<bean id="emailService"
   class="com.freetimelearn.app.EmailService">
</bean>
 
<bean id="customer"
   class="com.freetimelearn.app.Customer">
   <constructor-arg ref="emailService">
</bean>
 The above configuration file will be translated to the following by Spring.
EmailService theEmailService = new EmailService();
 
Customer theCustomer = new Customer(theEmailService);
If we have a base package com.freetimelearn.app, Spring will recursively scan for components starting from the base package through all directories until the required component is found.
 
A package com.freetimelearn.app.demo is a sub package because of the naming structure, just like folders on a file system.

Integrate data from multiple sources such as Data Access Objects (DAO) and repositories, service facade design pattern, and an Intermediate layer for custom business logic.
Since Spring is based on the concept of Dependency Injection, all the classes, interfaces, and their dependencies are stored in a file termed as the spring configuration file. It is a .xml file. The spring container uses this file to control the lifecycle of spring beans. A bean is configured as:
<bean id = "..." class = "..." init-method = "..." lazy-init="true" destroy-method="....">
      <!-- bean dependencies and configurations -->
</bean>
A JoinPoint is a point during the execution of a program and represents the method execution. It includes the execution of a method or even handling of an exception.
A proxy in the Spring framework is referred to as the creation of an object after applying advice to a particular target object. 
The target object and proxy object are the same in the case of client objects.
Weaving in Spring framework is the process of linking a particular aspect with other application types or objects so that an advised object is created. It is performed mostly during Runtime.
Reactive programming is a non-blocking and event-driven application. It scales with a small number of threads. The backpressure is on the key ingredient, which ascertains that the producers do not overwhelm consumers.
There are various benefits of Reactive Programming, which include the following.
 
* It helps in increasing the utilization of computing resources, including multicore and multi-CPU hardware.
* It helps in increasing performance by a reduction in the serialization process.
The important characteristics of the Reactive system includes the following :
 
* Message-driven.
* Resilient.
* Responsive.
* Elastic.
There are four types of autowiring in Spring framework.
 
* autowire byName
* autowire byType
* autowire by constructor
* autowiring by @Autowired and @Qualifier annotations

Prior to Spring 3.1, autowire by autodetect was also supported that was similar to autowire by constructor or byType.
DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initializes all the beans that are configured. If annotations are enabled, it also scans the packages and configures any bean annotated with @Component, @Controller, @Repository, or @Service annotations.
 
ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. Its important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to automate the creation of ApplicationContext. We can use it to define shared beans that can be used across different spring contexts.
ViewResolver implementations are used to resolve the view pages by name. We configure it in the spring bean configuration file. For example :
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>
 
InternalResourceViewResolver is one of the implementation of ViewResolver interface and we are providing the view pages directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will use view page located at /WEB-INF/views/home.jsp.
MultipartResolver interface is used for uploading files : CommonsMultipartResolver and StandardServletMultipartResolver are two implementations provided by spring framework for file uploading. By default there are no multipart resolvers configured but to use them for uploading files, all we need to define a bean named “multipartResolver” with type as MultipartResolver in spring bean configurations.
 
Once configured, any multipart request will be resolved by the configured MultipartResolver and pass on a wrapped HttpServletRequest. Then it’s used in the controller class to get the file and process it.
Spring DAO support allows for easier access to data technologies like JDO, Hibernate and JDBC. This support module also provides more consistent access to these technologies without having to worry about catching technology-specific exceptions.”
Spring supports the following ORM's :
 
* Hibernate
* iBatis
* JPA (Java Persistence API)
* TopLink
* JDO (Java Data Objects)
* OJB
* Before advice is run before the method.
* After returning advice which is run after the method successfully executes.
* After throwing advice which is run after the method if an exception is thrown.
* After finally advice is run after the method regardless of how a join point exists.
* Around advice is run before and after the method.
A pointcut is a predicate expression for where advice should be applied and uses AspectJ's pointcut expression language. It works in such a way that if certain conditions are met Spring AOP system will apply the given advice code.
Execution pointcut applies to the execution of a method, and we can use the following Pointcut expression language to match the method name.
execution(modifiers-pattern? return-type-pattern declaring-type-pattern?
   method-name-pattern(param-pattern) throws-pattern?)
 
The modifiers in Spring AOP only supports public, and return type can be void, boolean, List and others. The declaring type is the class name that you use for the given method, you can give the actual method name on the method name pattern or make use of wildcards. The method can be matched for a given parameter list using the param pattern, and finally, we have a throws pattern that throws a given exception. The pattern is optional if it has a question mark “?”.
 
@Before("execution(public void com.freetimelearn.app.CustomerDAO.addCustomer())")
 
In this example, we want to match on only the addCustomer method in the CustomerDAO class, and if those items match, then we will apply our advice for that Pointcut, and that is all for matching on execution calls for a given method name.
The open param, close param () is a parameter pattern which matches on a method with no arguments.

@Before("execution(* addCustomer())")​
 
The open param star, close param (*) is another pattern that matches a method with one argument of any type.
 
@Before("execution( * addCustomer(com.FreeTimeLearn.app.model.Customer))")
 
Finally, we have the open param dot dot, close param (..) which matches on a method with zero to many arguments of any type.
 
@Before("execution(* addCustomer(..))")
 
No, Spring 5 is not compatible with the older versions of JAVA. It requires at least JAVA 8 for attaining compatibility.
Yes, Spring Boot can allow either Spring MVC or Spring WebFlux in the same application but with the condition to apply only one at a time. This is because MVC is a blocking paradigm, and WebFlux is a non-blocking paradigm and hence cannot be used together.
Yes, Spring 5 could integrate with the Jdk9 Modularity. This can be stated as follows :
 
Step 1 : Creating a new class :
 
package com.hello;
public class HelloWorld {
    public String sayHello(){
        return "HelloWorld";
    }
}
 
Step 2 : Creating a new module :
 
module com.hello {
    export com.hello;
}
 
Step 3 : Creating a new Java Project :
 
module com.hello.client {
    requires com.hello;
}
 
Step 4 : Testing the new module :
 
public class HelloWorldClient {
    public static void main(String[] args){
        HelloWorld helloWorld = new HelloWorld();
        log.info(helloWorld.sayHello());
    }
}
The first way is to use <props> tag as below.
 
<bean id="adminUser" class="com.freetimelearn.common.Customer">
  
    <!-- java.util.Properties -->
    <property name="emails">
        <props>
            <prop key="admin">admin@nospam.com</prop>
            <prop key="support">support@nospam.com</prop>
        </props>
    </property>
 
</bean>
 
You can use the “util:” namespace as well to create properties bean from a properties file and use bean reference for setter injection.
 
<util:properties id="emails" location="classpath:com/foo/emails.properties" />

WebClient is a component in the new Web Reactive framework that can act as a reactive client for performing non-blocking HTTP requests. Since it's reactive client, it can handle reactive streams with back pressure, and it can take full advantage of Java 8 lambdas. It can also handle both sync and async scenarios.
 
On the other hand, the WebTestClient is a similar class that we can use in tests. Basically, it's a thin shell around the WebClient. It can connect to any server over an HTTP connection. It can also bind directly to WebFlux applications using mock request and response objects, without the need for an HTTP server.