Are you thinking of continuing your career with the Spring Framework? Looking for a Question Answer set that is suitable for preparing for a job interview? This is the Spring Interview Questions blog that explains the top questions with appropriate explanations and examples. It will definitely help you master the interview. But before we start with Spring Interview Questions, let’s take a quick look at the Spring Framework.
The Spring Framework is a lightweight and easy-to-build open-source framework that includes various frameworks such as dependency injection, Spring MVC, Spring JDBC, Spring Hibernate, Spring AOP, EJB, JSF, etc. You can also think of it as a framework for your work. An important element of Spring is the support capabilities of the application infrastructure. Spring focuses on providing “installations” of applications at the enterprise level, allowing developers to focus solely on application-level business logic without being unnecessarily tied to a particular deployment environment.
Applications developed in Spring are more reliable, scalable, and very easy to build and maintain. Spring is designed to allow developers to manage the business objects of their applications. Its rich features and flexibility have made Spring the most popular framework for developing enterprise-level Java-based applications. In the next section, we’ll look at some of the most common interview questions and answers in preparation for a spring interview.
1. What is Spring Framework?
Spring is one of the most widely used Java EE frameworks. The core concepts of the Spring framework are dependency injection and aspect-oriented programming. The Spring framework can also be used in regular Java applications, where you can implement dependency injection to achieve loose coupling between different components. You can also use Spring support for aspect-oriented programming to perform cross-cutting tasks such as logging and authentication.
2. What are some of the important features and advantages of Spring Framework?
The Spring Framework is based on two design concepts: Dependency Injection and Aspect-Oriented Programming. Some of the features of the
Some of the features of the spring framework are:
- Lightweight and with little overhead when using the framework for development.
- Dependency injection or inversion of control to create mutually independent components. SpringContainer connects them together to perform their work.
- The Spring IoC container manages the Spring Bean lifecycle and manages project-specific configurations such as JNDI lookups.
- You can use the Spring MVC framework to create web applications and restore web services that can return both XML and JSON responses.
- It uses either annotations or Spring Bean configuration files to support transaction management, JDBC operations, file uploads, exception handling, etc. with little configuration.
3. What do you understand by Dependency Injection?
At first, Dependency injection design patterns allow you to remove hard-coded dependencies, loosely couple applications, and make them extensible and easy to maintain. Then you can implement a dependency injection pattern to move dependency resolution from compile-time to run time. Finally, Some of the benefits of using Dependency Injection is the separation of concerns, reduction of boilerplate code, configurable components, and simple unit testing.
4. How do we implement DI in Spring Framework?
We can use Spring XML based as well as Annotation-based configuration to implement DI in spring applications.
5. Name some of the important Spring Modules?
Some of the important Spring Framework modules are:
- SpringContext – For dependency injection.
- SpringAOP – For aspect-oriented programming.
- SpringDAO – For database operations using the DAO pattern
- SpringJDBC – For JDBC and data source support.
- SpringORM – To support ORM tools such as Hibernate
- SpringWeb Module – For building web applications.
- SpringMVC – Implementation of ModelViewController for building web applications, web services, etc.
6. What do you understand by Aspect-Oriented Programming?
At first, Enterprise applications share some common cross-cutting themes that apply to different types of objects and application modules, including Logging, transaction management, data validation, authentication, etc. In object-oriented programming, application modularity is achieved through classes, while in AOP applications, modularity is achieved through aspects and is configured to penetrate different class methods. The
AOP removes the direct dependency of cross-cutting tasks on classes, which is not possible with normal object-oriented programming. For example, you can create another class for logging, but the class must call these methods to log the data.
7. What is Aspect, Advice, Pointcut, JointPoint, and Advice Arguments in AOP?
- 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 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
- Pointcut: Pointcut is 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.
- Join Point: 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.
8. What is the difference between Spring AOP and AspectJ AOP?
AspectJ is an industry-standard implementation of aspect-oriented programming, but Spring implements AOP in some cases. The main differences between Spring AOP and AspectJ are:
- SpringAOP is easier to use than AspectJ because you don’t have to worry about the weaving processes.
- Spring AOP supports AspectJ annotations. Therefore, if you are familiar with AspectJ, working with Spring AOP is easy.
- Spring AOP only supports proxy-based AOP, so it can only be applied to method execution connection points.
- AspectJ supports all kinds of pointcuts. One of the drawbacks of Spring AOP is that it can only be applied to beans built via SpringContext.
9. What is Spring IoC Container?
Inversion of control (IoC) is a mechanism that achieves loose coupling between object dependencies. Objects define dependencies to achieve a loose coupling and dynamic binding of objects at run time. Dependencies are injected by other assembler objects. Spring IoC Container is a program that inserts dependencies into objects and makes them available. The
Spring Framework IoC container class is part of the org.springframework.beans and org.springframework.context packages and provides different ways to isolate object dependencies.
Some of the useful ApplicationContext implementations we use are:
- AnnotationConfigApplicationContext: For standalone Java applications with annotation-based configurations.
- ClassPathXmlApplicationContext: For standalone Java applications with XML-based configurations.
- FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext, except that the XML configuration file can be loaded from anywhere in the file system.
- AnnotationConfigWebApplicationContext and XmlWebApplicationContext: For Web application.
10. What is a Spring Bean?
Any normal java class that is initialized by the Spring IoC container is called Spring Bean. We use Spring ApplicationContext to get the Spring Bean instance. Spring IoC container manages the life cycle of Spring Bean, bean scopes, and injecting any required dependencies in the bean.
11. What is the importance of the Spring bean configuration file?
Use the Spring Bean configuration file to define all the beans that are initialized by the Spring Context. When you create a Spring ApplicationContext instance, the Spring Bean XML files are read and all of them are initialized. Once the context is initialized, you can use it to get various bean instances.
In addition to the Spring Bean configuration, this file also contains Spring MVC interceptors, view resolvers, and other elements that support annotation-based configurations.
12. What are the different scopes of Spring Bean?
Five areas are defined in SpringBean, they are:
- Singleton: Only one instance of the bean is created per container. This is the standard range of spring beans. When using this scope, make sure your Spring beans don’t have shared instance variables. Otherwise, it is not thread-safe and may cause data inconsistencies.
- Prototype: A new instance is created each time a bean is requested.
- Request: This is the same as the prototype area, but for web applications. A new instance of the bean is created for each HTTP request.
- Session: A new bean is created by the container for each HTTP session.
- Global-session: This is used to create a global session bean for the portlet application. The Spring Framework is extensible and you can create your own scope, but in most cases the scope provided by the framework is fine.
To set the Spring Bean scope, you can use the Bean element’s “Scope” attribute or the @Scope annotation in the annotation-based configuration.
13. What is Spring Bean’s life cycle?
The Spring Bean is initialized by the Spring Container and all dependencies are also injected. When the context is destroyed, all initialized beans are also destroyed. This works fine in most cases, but you may want to initialize other resources or perform validation before making the bean available. The Spring Framework provides post-initialization and pre-destruction method support for Spring Beans.
This can be done in two ways: by implementing the Initializing Bean and Disposable Bean interfaces, or by using the init-method and destroy-method attributes in the Spring Bean configuration.
14. How to get ServletContext and ServletConfig object in a Spring Bean?
There are two ways to get Container specific objects in the spring bean.
- Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for a complete example of these aware interfaces,
- Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container-specific environments only though.
15. What is Bean wiring and @Autowired annotation?
The process of injecting SpringBean dependencies during initialization is known as SpringBeanWiring.
It’s usually best to explicitly link all bean dependencies, but the Spring framework also supports automatic linking. The @Autowired annotation can be used in a field or method of automatic wiring by type. For this annotation to work, you also need to enable annotation-based configuration in the Spring Bean configuration file. This can be done via the context: annotation-config element.
16. What are the different types of Spring Bean autowiring?
There are four types of autowiring in Spring framework.
- 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.
17. Does Spring Bean provide thread-safety?
The default scope for Spring beans is a singleton, so there is only one instance per context. Obviously, This means that the data will be inconsistent if all class-level variables that each thread can update are present. Therefore, Spring Bean in standard mode is not thread-safe.
However, you can change the Spring Bean scope depending on the request, prototype, or session to achieve thread safety at the expense of performance. Finally, This is a design decision and is based on the requirements of the project.
18. What is a Controller in Spring MVC?
Just like MVC the design pattern, Controller is the class that takes care of all the client requests and send them to the configured resources to handle it. In Spring MVC, org.springframework.web.servlet.DispatcherServlet is the front controller class that initializes the context based on the spring beans configurations.
A Controller class is responsible to handle different kind of client requests based on the request mappings. We can create a controller class by using @Controller annotation. Usually it`s used with @RequestMapping annotation to define handler methods for specific URI mapping.
19. What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?
- @Component is used to indicate that a class is a component. These classes are used for auto-detection and configured as a bean when annotation-based configurations are used. @Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.
- @Repository annotation is used to indicate that a component is used as a repository and a mechanism to store/retrieve/search data. Moreover, We can apply this annotation with DAO pattern implementation classes.
- @Service is used to indicate that a class is a Service. Usually, the business facade classes that provide some services are annotated with this.
We can use any of the above annotations for a class for auto-detection but different types are provided so that you can easily distinguish the purpose of the annotated classes.
20. What are DispatcherServlet and ContextLoaderListener?
- 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.
21. How to create ApplicationContext in a Java Program?
You can create a Spring context in a standalone Java program by:
- AnnotationConfigApplicationContext: If you use Spring in a standalone Java application and use annotations in your configuration, you can use it to initialize the container and get the Bean object.
- ClassPathXmlApplicationContext: If your standalone application has a Spring Bean configuration XML file, you can use this class to load the file and get the container object.
- FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext, except that the XML configuration file can be loaded from anywhere in the file system.
22. What are the minimum configurations needed to create a Spring MVC application?
To create a simple Spring MVC application, you need to perform the following tasks:
- At first, Added Spring-Context and Spring-WebMVC dependencies to projects.
- Secondly, Configure DispatcherServlet in the web.xml file to handle requests through the Spring container.
- Then, Spring Bean configuration file for defining beans.
- But If you want to use annotations, you need to configure them here.
- You also need to configure the view resolver for the view page.
- Finally, A controller class with a request map defined to handle client requests.
- Undoubtedly, if you have done all above steps should be sufficient to create a simple Spring MVCHelloWorld application.
23. How would you relate Spring MVC Framework to MVC architecture?
As well as the name implies, Spring MVC is based on the Model-View-Controller architecture. Then the DispatcherServlet is the front controller for Spring MVC applications, handles all incoming requests, and delegates them to various controller handler methods. While the model can be any Java Bean in the Spring framework, just like any other MVC framework. Apart from this Spring provides automatic binding of form data to JavaBeans. Moreover, you can set the model bean as an attribute to use on the view page. The view page can be JSP, static HTML, and so on. The view resolver is responsible for finding the correct view page. Once the view page is identified, control is returned to the DispatcherServlet controller. The DispatcherServlet is responsible for rendering the view and returning the final response to the client.
24. What are some of the important Spring annotations you have used?
Some of the Spring annotations that I have used in my project are:
@Controller – for controller classes in the Spring MVC project.
@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation.
@ResponseBody – for sending Object as a response, usually for sending XML or JSON data as a response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
@Autowired – for autowiring dependencies in spring beans.
@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
@Service – for service classes.
@Scope – for configuring the scope of the spring bean.
@Configuration, @ComponentScan, and @Bean – for java based configurations.
AspectJ annotations for configuring aspects and advice, @Aspect, @Before, @After, @Around, @Pointcut, etc.
25. How would you achieve Transaction Management in Spring?
At first, the Spring framework provides transaction management support through declarative transaction management and programmatic transaction management. Declarative transaction management is most commonly used because it is easy to use and works in most cases.
Then, For declarative transaction management, use the annotation method with the @Transactional annotation. Finally, You need to configure the data source transaction manager in the SpringBean configuration file.
|<bean id=”transactionManager” class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”> |
<property name=”dataSource” ref=”dataSource” />
26. What is Spring DAO?
Spring DAO support is provided to work with data access technologies such as JDBC and Hibernate in a consistent and easy way. For example, related technologies include JdbcDaoSupport, HibernateDaoSupport, JdoDaoSupport, and JpaDaoSupport. Spring DAO also provides consistency in the exception hierarchy and you don’t have to catch any particular exception.
27. How to integrate Spring and Hibernate Frameworks?
At first, You can use the Spring ORM module to integrate the Spring framework with the Hibernate framework. Then, If SessionFactory is using Hibernate 3 +, which serves the current session, you should avoid using the HibernateTemplate or HibernateDaoSupport classes and use the DAO pattern with dependency injection more appropriately for integration.
Also, the Spring ORM supports the use of Spring’s declarative transaction management, so you should use it instead of using boilerplate code for transaction management hibernation.
28. Name some of the design patterns used in Spring Framework?
Spring Framework is using a lot of design patterns, some of the common ones are:
- Singleton Pattern: Creating beans with default scope.
- Factory Pattern: Bean Factory classes.
- Prototype Pattern: Bean scopes.
- Adapter Pattern: Spring Web and Spring MVC.
- Proxy Pattern: Spring Aspect Oriented Programming support.
- Template Method Pattern: JdbcTemplate, HibernateTemplate, etc.
- Front Controller: Spring MVC DispatcherServlet.
- Data Access Object: Spring DAO supports Dependency Injection and Aspect-Oriented Programming.