Spring Interview Questions & Answers

Below are Top Spring Interview Questions based on the candidate's experiences and the company's interview pattern.  


 

1. What is a Spring Framework?

1) Spring is a powerful open-source, application framework created to reduce the complexity of enterprise application development.

2) It is light-weighted and loosely coupled.

3) It has layered architecture, which allows you to select the components to use, while also providing a cohesive framework for J2EE application development.

4) Spring framework is also called the framework of frameworks as it provides support to various other frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc.

 

2. List the advantages of Spring Framework.

1) Because of Spring Frameworks layered architecture, you can use what you need and leave what you don’t.

2) Spring Framework enables POJO (Plain Old Java Object) Programming which in turn enables continuous integration and testability.

3) JDBC is simplified due to Dependency Injection and Inversion of Control.

4) It is open-source and has no vendor lock-in.

 

3. What are the different features of Spring Framework?

Following are some of the major features of Spring Framework :

1) Lightweight: Spring is lightweight when it comes to size and transparency. 

2) Inversion of control (IOC): The objects give their dependencies instead of creating or looking for dependent objects. This is called Inversion of Control.

Aspect-oriented programming (AOP): Aspect-oriented programming in Spring supports cohesive development by separating application business logic from system services.

3) Container: Spring Framework creates and manages the life cycle and configuration of the application objects.

4) MVC Framework: Spring Framework’s MVC web application framework is highly configurable. Other frameworks can also be used easily instead of Spring MVC Framework.

5) Transaction Management: Generic abstraction layer for transaction management is provided by the Spring Framework. Spring’s transaction support can be also used in container-less environments.

6) JDBC Exception Handling: The JDBC abstraction layer of the Spring offers an exception hierarchy, which simplifies the error handling strategy.

 

4. What is a Spring configuration file?

A Spring configuration file is an XML file. This file mainly contains the classes information. It describes how those classes are configured as well as introduced to each other. The XML configuration files, however, are verbose and cleaner. If it’s not planned and written correctly, it becomes very difficult to manage big projects.

 

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

A Spring application generally consists of the following components:

 

1) Interface: It defines the functions.

2) Bean class: It contains properties, its setter and getter methods, functions, etc.

3) Spring Aspect-Oriented Programming (AOP): Provides the functionality of cross-cutting concerns.

4) Bean Configuration File: This contains the information of classes and how to configure them.

5) User program: It uses the function.

 

6. What are the various ways of using Spring Framework?

Spring Framework can be used in various ways. They are listed as follows:

 

1) As a Full-fledged Spring web application.

2) As a third-party web framework, using Spring Frameworks middle-tier.

3) For remote usage. 

4) As Enterprise Java Bean which can wrap existing POJOs (Plain Old Java Objects).

 

7. What is Spring IOC Container?

At the core of the Spring Framework, lies the Spring container. The container creates the object, wires them together, configures them, and manages their complete life cycle. The Spring container makes use of Dependency Injection to manage the components that make up an application. The container receives instructions for which objects to instantiate, configure, and assemble by reading the configuration metadata provided. This metadata can be provided either by XML, Java annotations, or Java code.

 

8. What do you mean by Dependency Injection?

In Dependency Injection, you do not have to create your objects but have to describe how they should be created. You don’t connect your components and services together in the code directly, but describe which services are needed by which components in the configuration file. The IoC container will wire them up together.

 

9. In how many ways can Dependency Injection be done?

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

 

1) Constructor Injection

2) Setter Injection

3) Interface Injection

4) In Spring Framework, only constructor and setter injections are used.

 

10. How many types of IOC containers are there in spring?

1) BeanFactory: BeanFactory is like a factory class that contains a collection of beans. It instantiates the bean whenever asked for by clients.

2) ApplicationContext: The ApplicationContext interface is built on top of the BeanFactory interface. It provides some extra functionality on top BeanFactory.

 

11.  List some of the benefits of IoC.

Some of the benefits of IoC are:

1) It will minimize the amount of code in your application.

2) It will make your application easy to test because it doesn’t require any singletons or JNDI lookup mechanisms in your unit test cases.

3) It promotes loose coupling with minimal effort and the least intrusive mechanism.

4) It supports eager instantiation and lazy loading of the services.

 

12. Differentiate between BeanFactory and ApplicationContext.

1) Spring BeanFactory Container: This is the simplest container providing the basic support for DI (dependency injection) and is defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward compatibility with a large number of third-party frameworks that integrate with Spring.

 

2) Spring ApplicationContext Container: This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface.

13. List some of the benefits of IoC.

 Some of the benefits of IoC are:

1)     It will minimize the amount of code in your application.

2)     It will make your application easy to test because it doesn’t require any singletons or JNDI lookup mechanisms in your unit test cases.

3)     It promotes loose coupling with minimal effort and the least intrusive mechanism.

4)     It supports eager instantiation and lazy loading of the services.

 

14. What are Spring Beans?

1) They are the objects that form the backbone of the user’s application.

2) Beans are managed by the Spring IoC container.

3) They are instantiated, configured, wired, and managed by a Spring IoC container

4) Beans are created with the configuration metadata that the users supply to the container.

 

15. How configuration metadata is provided to the Spring container?

Configuration metadata can be provided to the Spring container in the following ways:

 

1) XML-Based configuration: In Spring Framework, the dependencies and the services needed by beans are specified in configuration files which are in XML format. These configuration files usually contain a lot of bean definitions and application specific configuration options. They generally start with a bean tag. For example:

 

<bean id="studentbean" class="com.StudentBean">

 <property name="name" value="John"></property>

</bean>

 

2) Annotation-Based configuration: Instead of using XML to describe a bean wiring, you can configure the bean into the component class itself by using annotations on the relevant class, method, or field declaration. By default, annotation wiring is not turned on in the Spring container. So, you need to enable it in your Spring configuration file before using it. For example:

 

<beans>

<context:annotation-config/>

<!-- bean definitions go here -->

</beans>

 

3) Java-based configuration: The key features in Spring Framework’s new Java-configuration support are @Configuration annotated classes and @Bean annotated methods.

1. @Bean annotation plays the same role as the <bean/> element.

2. @Configuration classes allow defining inter-bean dependencies by simply calling other @Bean methods in the same class.

 

16. How many bean scopes are supported by Spring?

The Spring Framework supports five scopes. They are:

 

1) Singleton: This provides scope for the bean definition to a single instance per Spring IoC container.

2) Prototype: This provides scope for a single bean definition to have any number of object instances.

3) Request: This provides scope for a bean definition to an HTTP request. 

4) Session: This provides scope for a bean definition to an HTTP session. 

5) Global-session: This provides scope for a bean definition to a Global HTTP session. 

 

17. What is the Bean life cycle in Spring Bean Factory Container?

Bean life cycle in Spring Bean Factory Container is as follows:

 

1) The Spring container instantiates the bean from the bean’s definition in the XML file.

2) Spring populates all of the properties using the dependency injection, as specified in the bean definition.

3) The factory calls setBeanName() by passing the bean’s ID if the bean implements the BeanNameAware interface.

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

5) preProcessBeforeInitialization() methods are called if there are any BeanPostProcessors associated with the bean.

6) If an init-method is specified for the bean, then it will be called.

7) Finally, postProcessAfterInitialization() methods will be called if there are any BeanPostProcessors associated with the bean.

 

18. Define Bean Wiring?

When beans are combined together within the Spring container, it’s called wiring or bean wiring. The Spring container needs to know what beans are needed and how the container should use dependency injection to tie the beans together, while wiring beans.

 

19. What do you understand by auto wiring and name the different modes of it?

The Spring container is able to autowire relationships between the collaborating beans. That is, it is possible to let Spring resolve collaborators for your bean automatically by inspecting the contents of the BeanFactory.

Different modes of bean auto-wiring are:

 

1) no: This is the default setting which means no autowiring. An explicit bean reference should be used for wiring.

2) byName: It injects the object dependency according to name of the bean. It matches and wires its properties with the beans defined by the same names in the XML file.

3) byType: It injects the object dependency according to type. It matches and wires a property if its type matches with exactly one of the bean's names in the XML file.

4) constructor: It injects the dependency by calling the constructor of the class. It has a large number of parameters.

5) autodetect: First the container tries to wire using autowire by the constructor, if it can’t then it tries to autowire by byType.

 

20. What are the limitations with auto wiring?

Following are some of the limitations you might face with auto wiring:

 

1) Overriding possibility: You can always specify dependencies using <constructor-arg> and <property> settings which will override autowiring.

2) Primitive data type: Simple properties such as primitives, Strings, and Classes can’t be autowired.

3) Confusing nature: Always prefer using explicit wiring because autowiring is less precise.

 

21. What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?

1) @Component: This marks a java class as a bean. It is a generic stereotype for any Spring-managed component. The component-scanning mechanism of spring now can pick it up and pull it into the application context.

 

2) @Controller: This marks a class as a Spring Web MVC controller. Beans marked with it are automatically imported into the Dependency Injection container.

 

3) @Service: This annotation is a specialization of the component annotation. It doesn’t provide any additional behavior over the @Component annotation. You can use @Service over @Component in service-layer classes as it specifies intent in a better way.

 

4) @Repository: This annotation is a specialization of the @Component annotation with similar use and functionality. It provides additional benefits specifically for DAOs. It imports the DAOs into the DI container and makes the unchecked exceptions eligible for translation into Spring DataAccessException.

 

22. What do you understand by @Required annotation?

@Required is applied to bean property setter methods. This annotation simply indicates that the affected bean property must be populated at the configuration time with the help of an explicit property value in a bean definition or with autowiring. If the affected bean property has not been populated, the container will throw BeanInitializationException.

 

23. What do you understand by @Autowired annotation?

The @Autowired annotation provides more accurate control over where and how autowiring should be done. This annotation is used to autowire bean on the setter methods, constructor, a property, or methods with arbitrary names or multiple arguments. By default, it is a type-driven injection.

Example: 

 

public class A

{

private String city;

@Autowired

public void setCity(String city)

{this.city=city; }

public string getCity()

{ return city; }

}

 

24. What do you understand by @Qualifier annotation?

When you create more than one bean of the same type and want to wire only one of them with a property you can use the @Qualifier annotation along with @Autowired to remove the ambiguity by specifying which exact bean should be wired.

 

For example, here we have two classes, Employee and EmpAccount respectively. In EmpAccount, using @Qualifier its specified that bean with id emp1 must be wired.

 

25. Name the types of transaction management that Spring supports.

Two types of transaction management are supported by Spring. They are:

 

1) Programmatic transaction management: In this, the transaction is managed with the help of programming. It provides you extreme flexibility, but it is very difficult to maintain.

2) Declarative transaction management: In this, the transaction management is separated from the business code. Only annotations or XML-based configurations are used to manage the transactions.

 

26. What is Spring AOP?

Aspect-oriented Programming is a programming paradigm that is analogous to object-oriented programming. A key unit of object-oriented programming is class, similarly, the key unit for AOP is Aspect. Aspect enables modularisation of concerns such as transaction management, it cut across multiple classes and types. It also refers to cross-cutting concerns.

 

27. Are Singleton Beans Thread-Safe?

No, singleton beans are not thread-safe, as thread safety is about execution, whereas singleton is a design pattern focusing on creation. Thread safety depends only on the bean implementation itself.

 

28. Can We Have Multiple Spring Configuration Files in One Project?

Yes, in large projects, having multiple Spring configurations is recommended to increase maintainability and modularity.

 

You can load multiple Java-based configuration files:

 

@Configuration

@Import({MainConfig.class, SchedulerConfig.class})

public class AppConfig {

Or load one XML file that will contain all other configs:

 

ApplicationContext context = new ClassPathXmlApplicationContext("spring-all.xml");

 

29. What Is Spring Security?

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, you can get started with a simple annotation: @EnableWebSecurity.

 

30. What Is Spring Boot?

Spring Boot is a project that provides a pre-configured set of frameworks to reduce boilerplate configuration so that you can have a Spring application up and running with the smallest amount of code.