45 Spring Interview Questions And Answers

45 Spring Interview Questions And Answers For Experienced from Codingcompiler. Test your Spring framework knowledge by answering these tricky interview questions on Spring Framework. Let’s start learning Java Spring interview questions and prepare for Spring framework interviews. All the best for your future and happy learning.

Spring Interview Questions

  1. Tell us about the Spring Framework.
  2. What are some of the important features and benefits of the Spring Framework?
  3. What do you understand as Dependency Injection (DI)?
  4. How is DI implemented in the Spring Framework?
  5. What are the benefits of using Spring Tool Suite?
  6. Give the names of some important Spring modules.
  7. What do you mean by Aspect Oriented Programming (AOP)?
  8. What are Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?
  9. What is the difference between Spring AOP and AspectJ AOP?
  10. What is Spring’s IoC container?
  11. What is Spring Bin?
  12. How important is the Spring Bean configuration file?
  13. What are the different ways to set up a class like Spring Bean?
  14. What do you know about the different scope of Spring Bean?
  15. What is the life cycle of Spring Bean?
  16. How to get the ServletContext and ServletConfig objects inside Spring Bean?
  17. What is binding in Spring and tell us about the @Autowired annotation?
  18. What are the different types of automatic binding in Spring?
  19. Is Spring Bin thread-safe?
  20. What is a controller in Spring MVC?
  21. What is the difference between the @Component, @Repository and @Service annotations in Spring?
  22. Tell us what you know about DispatcherServlet and ContextLoaderListener.
  23. What is a ViewResolver in Spring?
  24. What is MultipartResolver and when to use it?
  25. How to handle exceptions in the Spring MVC Framework?
  26. How to create an ApplicationContext in a Java program?
  27. Can we have multiple Spring configuration files?
  28. What are the minimum settings to create a Spring MVC application?
  29. How would you link the Spring MVC Framework and MVC architecture?
  30. How to achieve localization in Spring MVC applications?
  31. How can we use Spring to create a RESTful web service that returns JSON?
  32. Give an example of frequently used Spring annotations.
  33. Can we send an object as a response to the controller’s handler method?
  34. How to upload a file to Spring MVC?
  35. How to check (validate) the form data in the Spring Web MVC Framework?
  36. What do you know the Spring MVC Interceptor and how is it used?
  37. Spring JdbcTemplate class and its application.
  38. How to use Tomcat JNDI DataSource in a Spring web application?
  39. How can I manage transactions in Spring?
  40. Tell us about Spring DAO.
  41. How to integrate Spring and Hibernate?
  42. Tell us about Spring Security.
  43. How to embed java.util.Properties in Spring Bean?
  44. What are some of the design patterns used in the Spring Framework?
  45. Best Practices in the Spring Framework.

Spring Interview Questions And Answers

1. Tell us about the Spring Framework.

The Spring Framework (or Spring for short) is a universal open source framework for the Java platform. Although the Spring Framework does not provide any specific programming model, it has become widespread in the Java community mainly as an alternative and replacement for the Enterprise JavaBeans model.

The Spring Framework provides more freedom for Java developers to design; In addition, it provides well-documented and easy-to-use tools for solving problems encountered when creating enterprise-scale applications. Spring is usually described as a lightweight platform for building Java applications, but there are two interesting points to this statement.

First, Spring can be used to build any Java application (i.e., stand-alone, web applications, JEE applications, etc.), which distinguishes Spring from many other platforms, such as Apache Struts, which is limited only to web applications.

Secondly, the “lightweight” characteristic actually has nothing to do with the number of classes or the size of the distribution; on the contrary, it defines the principle of Spring’s entire philosophy — minimal impact.

The Spring platform is lightweight in the sense that to use the Spring kernel you must make minimal (if any) changes to the code of your application, and if at some point you decide not to use Spring anymore, then this is very easy to do. 

Note that this is only the Spring kernel — many additional components of Spring, such as access to the “lightweight” characteristic actually has nothing to do with the number of classes or the size of the distribution; on the contrary, it defines the principle of Spring’s entire philosophy — minimal impact.

2. What are some of the important features and benefits of the Spring Framework?

The Spring Framework provides solutions to many problems faced by Java developers and organizations that want to create an information system based on the Java platform. Due to the broad functionality, it is difficult to determine the most significant structural elements of which it is composed. The Spring Framework is not entirely related to the Java Enterprise platform, despite its extensive integration with it, which is an important reason for its popularity.

The Spring Framework is probably best known as a source of extensions (features) needed to effectively develop complex business applications outside the heavyweight software models that have historically dominated the industry. Another advantage is that he introduced previously unused functionality into today’s mainstream development methods, even outside of the Java platform.

This framework offers a consistent model and makes it applicable to most types of applications that are already based on the Java platform. It is believed that the Spring Framework implements a development model based on the best industry standards and makes it available in many areas of Java. Thus, the advantages of Spring include:

  • The relative ease of learning and applying the framework in the development and support of the application.
  • Dependency injection (DI) and inversion control (IoC) allow writing components that are independent of each other, which gives advantages in team development, module portability, etc.
  • The Spring IoC container manages the life cycle of Spring Bean and is configured like a JNDI lookup (search).
  • The Spring project contains many subprojects that affect important parts of creating software, such as web services, web programming, work with databases, file uploading, error handling, and much more. All this is configured in a uniform format and simplifies application support.

3. What do you understand as Dependency Injection (DI)?

Dependency injection (DI) is the process of providing external dependency to a software component. It is a specific form of “inversion of control” (IoC) when it is applied to dependency management. In full accordance with the principle of a single duty, the object gives care to build the dependencies required by it to an external, specially designed general mechanism for this. The advantages of using DI include:

  • Reducing the amount of glue code. One of the biggest advantages of DI is the ability to significantly reduce the amount of code that needs to be written to link together the various components of an application. Often this code is very simple – when creating a dependency, a new instance of the corresponding object should be created.
  • Simplified application configuration. By using DI, the application configuration process is greatly simplified. You can use annotations or XML files to configure classes that can be embedded in other classes.
  • The ability to manage general dependencies in a single repository. In the traditional approach to managing dependencies in shared services, which include, for example, connecting to a data source, transaction, remote services, etc., you create instances (or get them from certain factory classes) dependencies where they are needed – inside the dependent class. This leads to the spread of dependencies across multiple classes in the application, which can make it difficult to change them. If DI is used, all information about common dependencies is contained in a single repository (in Spring, it is possible to store this information in XML files or Java classes), which greatly simplifies dependency management and reduces the number of possible errors.
  • Improved testing capability. When classes are designed for DI, a simple replacement of dependencies becomes possible. This is especially useful when testing an application.
  • Stimulate quality design solutions for applications. Generally speaking, designing for DI means designing using interfaces. Using Spring, you have a whole range of DI tools at your disposal and can focus on building application logic, rather than on a DI-capable platform.

4. How is DI implemented in the Spring Framework?

Spring’s implementation of DI is based on two key concepts of Java — the JavaBean components and interfaces. When using Spring as a DI provider, you gain the flexibility to define dependency configurations within your applications in a variety of ways (that is, externally in XML files, using Spring Java configuration classes or using Java annotations in code).

JavaBean components (also called Plain Old Java Objects (plain old Java Objects)) provide a standard mechanism for creating Java resources that are configurable in a variety of ways. By using DI, the amount of code that is required when designing an application based on interfaces is reduced to almost zero. In addition, using interfaces you can get the most out of DI,

The types of implementation implementation dependencies in Spring include:

Constructor Dependency Injection is a type of dependency injection where component dependencies are provided to it in its constructor (or constructors).

1

2

3

4

5

6

7

8

public class ConstructorInjection {

private Dependency dependency;

 

 public ConstructorInjection(Dependency dependency) {

     this.dependency = dependency;

 }

}

Setter Dependency Injection  — The IoC container injects component dependencies into a component through JavaBean-style installation methods.

1

2

3

4

5

6

public class SetterInjection {

private Dependency dependency;

  public void setDependency(Dependency dependency) {

       this.dependency = dependency;

  }

}

5. What are the benefits of using Spring Tool Suite?

To simplify the process of developing Spring-based applications in Eclipse (the most commonly used free IDE for developing Java applications), the Spring IDE project was created as part of Spring. The project is free. It is integrated into Eclipse IDE, Spring IDE, Mylyn (Eclipse task-based development environment), Maven for Eclipse, AspectJ Development Tool.

Java Spring Interview Questions And Answers

6. Give the names of some important Spring modules.

  • Inversion of Control-container: configuring application components and managing the life cycle of Java objects.
  • Aspect-oriented programming framework: works with functionality that cannot be implemented with lossless object-oriented programming features in Java.
  • Data Access Framework: works with relational database management systems on the Java platform, using JDBC and ORM tools and providing solutions to problems that are repeated in a large number of Java-based environments.
  • Transaction Management Framework: Coordinating various transaction management APIs and custom transaction management tools for Java objects.
  • MVC framework: a framework based on HTTP and servlets, providing many possibilities for customization.
  • Remote access framework: configurable transfer of Java objects over an RPC-style network that supports RMI, CORBA, HTTP-based protocols, including web services (SOAP).
  • Authentication and authorization framework: configurable tools for authentication and authorization processes, supporting many popular and industry-standard protocols, tools, practices through the Spring Security subsidiary project (formerly known as Acegi).
  • Remote Management Framework: configurable representation and management of Java objects for local or remote configuration using JMX.
  • Messaging framework: configurable registration of message listener objects for transparent processing of messages from a message queue using JMS, improved sending of messages using the JMS API standard.
  • Testing: A framework that supports classes for writing unit and integration tests.

7. What do you mean by Aspect Oriented Programming (AOP)?

Aspect-oriented programming (AOP) is one of the “current programming models” in the Java world. AOP provides the ability to implement pass-through logic — i.e. logic, which applies to many parts of the application – in one place and ensure the automatic application of this logic throughout the application. Spring’s approach to AOP is to create “dynamic proxies” for target objects and “bind” objects to a configured board for performing end-to-end logic.

8. What are Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?

  • Connection points . The connection point ( JoinPoint ) – it is a clearly defined point at runtime. Typical examples of connection points include a call to the method, the Method Invocation itself, the initialization of the class, and the creation of an object instance. Connection points are the key concept of AOP and determine where in the application additional logic can be inserted using AOP.
  • Advice (advice) . A snippet of code that must be executed at a single connection point is a advice. There are several types of tips, among which are before, when the tip is executed to the junction point, and after, when the tip is executed after the junction point. In OOP, the council takes the form of a method within a class.
  • Slices . A pointcut is a collection of join points that is used to determine when a tip should be executed. By creating slices, you get precise control over how to apply the tip to the application components. As mentioned earlier, the typical connection point is Method Invocation. A typical slice is a collection of all Method Invocation connection points in a separate class. Often, complex relationships can be established between slices to provide additional constraints on when the advice will be executed.
  • Aspects . An aspect is a combination of board and slices. This combination results in a definition of the logic to be included in the application, and an indication of where it should be performed.
  • Binding . Binding ( weaving ) is the process of inserting the real dimensions in a certain point of application code. For AOP compile-time solutions, this is done at compile time, usually as an additional step of the build process. Similarly, for AOP runtime decisions, the binding occurs dynamically at run time. AspectJ supports another binding mechanism called load-time weaving (LTW), which intercepts the underlying JVM class loader and provides a binding to the bytecode when it is loaded by the class loader.
  • Goal . A target is an object whose execution flow is altered by some AOP process. The target object is often referred to as an object provided with advice.
  • Introduction . An introduction is a process through which you can change the structure of an object by introducing additional methods or fields into it. Introduction can be used to ensure that any object implements a specific interface without the need for the class of this object to implement such an interface explicitly.

9. What is the difference between Spring AOP and AspectJ AOP?

AspectJ is de facto the AOP implementation standard. The implementation of AOP from Spring has some differences:

  • Spring AOP is a bit simpler, because No need to follow the binding process.
  • Spring AOP supports AspectJ annotations, so we can work in a spring project in a similar way with the AspectJ project.
  • Spring AOP only supports proxy-based AOP and can use only one type of connection point – Method Invocation. AspectJ supports all kinds of connection points.
  • The disadvantage of the Spring AOP is to work only with its bins, which exist in the Spring Context.

10. What is Spring’s IoC container?

At its core, IoC, and, therefore, DI, aims to offer a simple mechanism for providing component dependencies (often called object collaborators) and managing these dependencies throughout their life cycle.

A component that requires certain dependencies is often called a dependent object or, in the case of IoC, a target object. It is appropriate now to state that IoC provides services through which components can access their dependencies, and services for interacting with dependencies during their lifetime.

In general, IoC can be split into two subtypes: control inversion ( Dependency Injection ) and dependency search ( Dependency Lookup). Control inversion is a big part of what Spring does, and the core of the Spring implementation is based on control inversion, although Dependency Lookup tools are also provided.

When the Spring framework automatically provides collaborators to a dependent object, it does so using inversion control (Dependency Injection). In a Spring-based application, it is always preferable to use Dependency Injection to send collaborators to dependent objects instead of forcing dependent objects to receive collaborators through a search.

Spring Framework Interview Questions And Answers

11. What is Spring Bin?

The term Spring bin is used to refer to any container-managed component . Usually, beans at a certain level adhere to the JavaBean specification, but this is not necessary especially if you plan to use Constructor Injection to bind the beans to each other. To get an instance of a bean, use ApplicationContext. The IoC container manages the spring bin life cycle, scope, and deployment.

12. How important is the Spring Bean configuration file?

The configuration file spring defines all the bins that will be initialized in the Spring Context. When creating an instance of Spring, the ApplicationContext will read the configuration xml file and perform the necessary initializations specified in it. Separate from the basic configuration, the file may contain a description of interceptors (interceptors), view resolvers, localization settings, etc.

13. What are the different ways to set up a class like Spring Bean?

There are several ways to work with classes in Spring:

XML configuration :

1 <bean name=”myBean” class=”ru.javastudy.spring.beans.MyBean”></bean>

Java based configuration . All settings and bins instructions are written in java code:

1

2

3

4

5

6

7

8

9

@Configuration

@ComponentScan(value=”ru.javastudy.spring.main”)

public class MyConfiguration {

   @Bean

   public MyService getService(){

       return new MyService();

   }

}

To extract a bean from the context, use the following approach:

1

2

3

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(

       MyConfiguration.class);

MyService service = ctx.getBean(MyService.class);

Annotation based configuration . Inside the code, you can use annotations @Component, @Service, @Repository, @Controller to specify classes as spring beans. To find them and manage the container, the setting is written in the xml file:

1 <context:component-scan base-package=”ru.javastudy.spring” />

14. What do you know about the different scope of Spring Bean?

Spring provides various time domains for bins:

  1. singleton – only one instance of the bean can be created. This type is used by default spring unless otherwise specified. You should carefully use the public properties of the class, because they will not be thread safe.
  2. prototype – a new instance is created with each request .
  3. request is similar to prototype, but the name serves as an explanation for using a bean in a web application . A new instance is created at every HTTP request.
  4. session  – a new bean is created in the container for each new HTTP session.
  5. global session : used to create global session-level bins for portlet applications.

15. What is the life cycle of Spring Bean?

The life cycle of a Spring bean is the lifetime of the class. Spring beans are initialized when the Spring container is initialized and all dependencies are injected. When a container is destroyed, all its contents are destroyed.

If we need to specify an action when initializing and destroying a bean, then we need to use the init () and destroy () methods . For this, you can use the @PostConstruct and @PreDestroy ()annotations .

1

2

3

4

5

6

7

8

9

10

@PostConstruct

   public void init(){

       System.out.println(“Bean init method called”);

   }

   @PreDestroy

   public void destroy(){

       System.out.println(“Bean destroy method called”);

   }

Or via xml configuration:

1

2

3

4

<bean name=”myBean” class=”ru.javastudy.spring.MyBean”

       init-method=”init” destroy-method=”destroy”>

   <property name=”someProp” ref=”someProp”></property>

</bean>

16. How to get the ServletContext and ServletConfig objects inside Spring Bean?

There are two ways to get the main container objects inside the bean:

  • Implement one of the Spring * Aware ( ApplicationContextAware ,  ServletContextAware ,  ServletConfigAware , etc.) interfaces.
  • Use automatic linking @Autowired in the spring. The way it works is inside the spring container.
1

2

@Autowired

ServletContext servletContext;

17. What is binding in Spring and tell us about the @Autowired annotation?

The process of introducing dependencies into beans during initialization is called Spring Bean Wiring. It is considered good practice to specify explicit relationships between dependencies, but Spring has an additional @Autowired binding mechanism.

Annotation can be used over a field or method for linking by type. In order for the annotation to work, you need to specify small settings in the configuration file spring using the context: annotation-config element.

18. What are the different types of automatic binding in Spring?

There are four types of binding in the spring:

  • autowire byName,
  • autowire byType,
  • autowire by constructor,
  • autowiring by @Autowired and @Qualifier annotations

19. Is Spring Bin thread-safe?

By default, the bin is set as a singleton in Spring. Thus, all public class variables can be changed simultaneously from different places. So – no, it is not. However, by changing the scope of the bean to request , prototype , session, it will be thread-safe, but this will affect performance.

Spring MVC Interview Questions And Answers

20. What is a controller in Spring MVC?

The key interface in Spring MVC is Controller. The controller processes requests for actions performed by users in the user interface, interacting with the service level, updating the model and directing users to the appropriate views depending on the results of execution. Controller – control, connection between model and view.

The main controller in Spring MVC is  org.springframework.web.servlet.DispatcherServlet . It is specified by the @Controller annotation and is often used with the @RequestMapping annotation, which indicates which requests will be processed by this controller.

21. What is the difference between the @Component, @Repository and @Service annotations in Spring?

@Component is  used to specify the class as a spring component. When using annotation search, this class will be configured as a spring bean.

@Controller is a  special class type used in MVC applications. Handles requests and is often used with the @RequestMapping annotation.

@Repository  indicates that the class is used to work with searching, retrieving and storing data. Annotation can be used to implement the DAO pattern.

@Service  indicates that a class is a service for implementing business logic (in fact, it does not differ from Component, but simply helps the developer specify the semantic meaning of the class).

To specify a container for a bin class, you can use any of these annotations. But different names make it possible to distinguish the purpose of a particular class.

22. Tell us what you know about DispatcherServlet and ContextLoaderListener.

DispatcherServlet – dispatcher servlet. This servlet parses the requests and sends them to the appropriate controller for processing. In Spring MVC, the DispatcherServlet class is the central servlet that receives requests and sends them to the appropriate controllers.

In the Spring MVC application, there can be an arbitrary number of DispatcherServlet instances  designed for different purposes (for example, to process user interface requests, REST web service requests, etc.). Each DispatcherServlet instance has its own WebApplicationContext configuration that defines the characteristics of the servlet level, such as controllers that support the servlet, the display of handlers, the recognition of representations, internationalization, theme design, validation, type conversion and formatting, etc.

ContextLoaderListener – a listener at the start and end of the Spring WebApplicationContext root class . The main purpose is to link the life cycle of ApplicationContext and ServletContext , as well as the automatic creation of ApplicationContext . You can use this class to access bins from various spring contexts. Configured in web.xml :

1

2

3

4

5

6

7

8

<context-param>

   <param-name>contextConfigLocation</param-name>

   <param-value>/WEB-INF/spring/root-context.xml</param-value>

</context-param>

<listener>

   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

23. What is a ViewResolver in Spring?

ViewResolver is a view recognizer. The Spring MVC ViewResolver interface (from the org.springframework.web.servlet package ) supports the recognition of views based on the logical name returned by the controller. A variety of implementation classes are provided to support various presentation recognition mechanisms.

For example, the UrlBasedViewResolver class supports direct conversion of logical names to URLs. The ContentNegotiatingViewResolver  class supports dynamic recognition of views depending on the type of media supported by the client (XML, PDF, JSON, etc.).

There are also several implementations for integration with various presentation technologies, such as FreeMarker (FreeMarkerViewResolver ), Velocity ( VelocityViewResolver ) and JasperReports ( JasperReportsViewResolver ).

1

2

3

4

5

6

7

<!– Resolves views selected for rendering by @Controllers to .jsp resources

       in the /WEB-INF/views directory –>

   <bean

           class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>

             <property name=”prefix” value=”/WEB-INF/views/” />

             <property name=”suffix” value=”.jsp” />

   </bean>

InternalResourceViewResolver is an implementation of ViewResolver that allows you to find views that the controller returns for subsequent transition to it. Searches for a given path, prefix, suffix and name.

24. What is MultipartResolver and when to use it?

The MultipartResolver interface is used to download files. There are two implementations: CommonsMultipartResolver and StandardServletMultipartResolver, which allow the framework to load files. By default, this interface is not included in the application and you must specify it in the configuration file. Once configured, any download request will be sent to this interface.

1

2

3

4

5

6

7

<beans:bean id=”multipartResolver”

       class=”org.springframework.web.multipart.commons.CommonsMultipartResolver”>

     <!– setting maximum upload size –>

       <beans:property name=”maxUploadSize” value=”100000″ />

 </beans:bean>

25. How to handle exceptions in the Spring MVC Framework?

In Spring MVC, the HandlerExceptionResolver interface (from the org.springframework.web.servlet package ) is designed to work with unexpected exceptions that occur during the execution of handlers. By default, DispatcherServlet registers the class DefaultHandlerExceptionResolver (from the package org.springframework.web.servlet.mvc.support ). This recognizer handles certain standard Spring MVC exceptions by setting a special response status code. You can also implement your own exception handler by annotating the controller method using the @ExceptionHandler annotationand passing an exception type as an attribute. In general, exception handling can be described as follows:

Controller Based – specify methods for handling exceptions in the controller class. To do this, mark such methods with the @ExceptionHandlerannotation .

Global Exception Handler – for handling global exceptions the spring provides an annotation @ControllerAdvice .

HandlerExceptionResolver implementation – The Spring Framework provides the HandlerExceptionResolver interface  , which allows you to specify a global exception handler. The implementation of this interface can be used to create your own global exception handlers in an application.

26. How to create an ApplicationContext in a Java program?

In the independent Java program, ApplicationContext can be created as follows:

  1. AnnotationConfigApplicationContext : when using Spring as a stand-alone application, you can create and initialize a container using annotations.
  2. ClassPathXmlApplicationContext : the second approach uses an xml file in which the necessary settings are made, and then use the class to load the file and get the container object.
  3. FileSystemXmlApplicationContext : similar to the version with xml, but with the ability to download the configuration file from anywhere in the file system.

27. Can we have multiple Spring configuration files?

By specifying contextConfigLocation, you can specify multiple Spring configuration files. Parameters are separated by commas or spaces:

1

2

3

4

5

6

7

8

9

<servlet>

   <servlet-name>appServlet</servlet-name>

   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

   <init-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>/WEB-INF/spring/appServlet/servlet-context.xml,/WEB-INF/spring/appServlet/servlet-jdbc.xml</param-value>

   </init-param>

   <load-on-startup>1</load-on-startup>

</servlet>

The ability to specify several Spring Spring configuration files is supported:

1

2

3

4

<context-param>

   <param-name>contextConfigLocation</param-name>

   <param-value>/WEB-INF/spring/root-context.xml /WEB-INF/spring/root-security.xml</param-value>

</context-param>

Configuration file can be imported:

1 <beans:import resource=”spring-jdbc.xml”/>

28. What are the minimum settings to create a Spring MVC application?

To create a simple Spring MVC application, follow these steps:

  • Add spring-context and spring-webmvc dependencies to the project.
  • Specify DispatcherServlet in web.xml to process requests within the application.
  • Set the definition of spring bean (annotation or in xml). Add a view resolver definition to views.
  • Configure the controller class to handle client requests.

29. How would you link the Spring MVC Framework and MVC architecture?

  • Model (Model) is any Java bean in Spring. Inside the class, various attributes and properties can be defined for use in the view.
  • View (JSP page, HTML file, etc.) serve to display the necessary information to the user. The view passes request processing to the servlet manager (controller).
  • DispatcherServlet (Controller) is the main controller in the Spring MVC application, which processes all incoming requests and sends them to various controllers for processing to various methods.

Advanced Spring Interview Questions And Answers

30. How to achieve localization in Spring MVC applications?

Spring MVC provides a very simple and convenient application localization feature. To do this, do the following:

  • Create a resource bundle file in which various localized information will be specified.
  • Define a messageSource in a Spring configuration using the ResourceBundleMessageSource or ReloadableResourceBundleMessag eSource classes.
  • Define the localeResolver of the CookieLocaleResolver class to enable the ability to switch locale.
  • Using the spring element: message DispatcherServlet will determine in which place the localized message should be substituted in the response.
1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<beans:bean id=”messageSource”

   class=”org.springframework.context.support.ReloadableResourceBundleMessageSource”>

   <beans:property name=”basename” value=”classpath:messages” />

   <beans:property name=”defaultEncoding” value=”UTF-8″ />

</beans:bean>

<beans:bean id=”localeResolver”

   class=”org.springframework.web.servlet.i18n.CookieLocaleResolver”>

   <beans:property name=”defaultLocale” value=”en” />

   <beans:property name=”cookieName” value=”myAppLocaleCookie”></beans:property>

   <beans:property name=”cookieMaxAge” value=”3600″></beans:property>

</beans:bean>

<interceptors>

   <beans:bean

       class=”org.springframework.web.servlet.i18n.LocaleChangeInterceptor”>

       <beans:property name=”paramName” value=”locale” />

   </beans:bean>

</interceptors>

31. How can we use Spring to create a RESTful web service that returns JSON?

The Spring Framework allows you to create Restful web services and return data in JSON format. Spring provides integration with the Jackson JSON API for the ability to send JSON responses in a restful web service. To send a response in JSON format from a Spring MVC application, the following settings must be made:

  • Add dependencies to Jackson JSON. With maven, this is done like this:
1

2

3

4

5

6

<!– Jackson –>

<dependency>

   <groupId>com.fasterxml.jackson.core</groupId>

   <artifactId>jackson-databind</artifactId>

   <version>${jackson.databind-version}</version>

</dependency>

  • Configure the RequestMappingHandlerAdapter bean  in the Spring configuration file and set the messageConverters property to use the MappingJackson2HttpMessageConverter bean  .
1

2

3

4

5

6

7

8

9

10

11

12

<!– Configure to plugin JSON as request and response in method handler –>

<beans:bean class=”org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter”>

   <beans:property name=”messageConverters”>

       <beans:list>

           <beans:ref bean=”jsonMessageConverter”/>

       </beans:list>

   </beans:property>

</beans:bean>

 

<!– Configure bean to convert JSON to POJO and vice versa –>

<beans:bean id=”jsonMessageConverter” class=”org.springframework.http.converter.json.MappingJackson2HttpMessageConverter”>

</beans:bean>

  • In the controller, use the @ResponseBody annotation to return the Object :
1

2

3

4

5

6

@RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET)

public @ResponseBody Employee getEmployee(@PathVariable(“id”) int empId) {

   logger.info(“Start getEmployee. ID=”+empId);

     

   return empData.get(empId);

}

32. Give an example of frequently used Spring annotations.

  • @Controller is the controller front class in the Spring MVC project.
  • @RequestMapping – allows you to set the URI mapping template in the controller’s handler method.
  • @ResponseBody – allows you to send an Object in the response. Typically used to send XML or JSON data.
  • @PathVariable – sets a dynamic mapping of values ​​from a URI inside the arguments of a handler method.
  • @Autowired – used for automatic binding of dependencies in spring beans.
  • @Qualifier – used in conjunction with @Autowired to clarify the binding data when collisions are possible (for example, the same name \ type).
  • @Service – indicates that the class performs service functions.
  • @Scope – indicates the scope of spring bean.
  • @Configuration , @ComponentScan and  @Bean – for java based configurations.
  • AspectJ annotations for customizing aspects and advices, @Aspect , @Before , @After , @Around , @Pointcut  , etc.

33. Can we send an object as a response to the controller’s handler method?

Yes it is possible. For this, the @ResponseBody annotation is used . So you can send answers in the form of JSON, XML in restful web services.

34. How to upload a file to Spring MVC?

Inside the spring, there is a MultipartResolver interface  for file uploads. In fact, you need to configure the configuration file to specify the file upload handler, and then set the required method in the spring controller.

35. How to check (validate) the form data in the Spring Web MVC Framework?

Spring supports validation annotations from JSR-303, as well as the ability to create your own implementations of validator classes. Annotation example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

   @Size(min=2, max=30)

   private String name;

     

   @NotEmpty @Email

   private String email;

     

   @NotNull @Min(18) @Max(100)

   private Integer age;

     

   @NotNull

   private Gender gender;

     

   @DateTimeFormat(pattern=”MM/dd/yyyy”)

   @NotNull @Past

   private Date birthday;

36. What do you know about the Spring MVC Interceptor and how is it used?

Interceptors in Spring (Spring Interceptor) are analogous to Servlet Filter and allow you to intercept client requests and process them. You can intercept a client’s request in three places: preHandle, postHandle and afterCompletion.

  • preHandle – a method used to process requests that have not yet been passed to the controller’s handler method. Should return true for transmission to the next interceptor or to the handler method. False will indicate that the request is handled by the handler and there is no need to pass it on. The method has the ability to throw exceptions and forward errors to the view.
  • postHandle — Called after the handler method, but before processing the DispatcherServlet to pass to the view. Can be used to add parameters to a ModelAndView object .
  • afterCompletion – called after drawing the view.

To create a handler, you must extend the abstract class  HandlerInterceptorAdapter or implement the HandlerInterceptor interface  . You also need to specify the interceptors in the Spring configuration file.

1

2

3

4

5

6

7

<!– Configuring interceptors based on URI –>

   <interceptors>

       <interceptor>

           <mapping path=”/home” />

           <beans:bean class=”ru.javastudy.spring.RequestProcessingTimeInterceptor”></beans:bean>

       </interceptor>

   </interceptors>

37. Spring JdbcTemplate class and its application.

Spring provides excellent support for the JDBC API and offers the class utility JdbcTemplate , with which you can get rid of repeating similar code repeatedly in an application (such as open / closing connection ; ResultSet , PreparedStatement , etc.). To connect, you need to configure the spring configuration file and get the JdbcTemplate object  . For example.

spring.xml :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”https://www.springframework.org/schema/beans”

   xmlns:xsi=”https://www.w3.org/2001/XMLSchema-instance”

   xsi:schemaLocation=”https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd”>

   <bean id=”employeeDAO” class=”com.journaldev.spring.jdbc.dao.EmployeeDAOImpl”>

       <property name=”dataSource” ref=”dataSource” />

   </bean>

   <bean id=”dataSource” class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>

       <property name=”driverClassName” value=”com.mysql.jdbc.Driver” />

       <property name=”url” value=”jdbc:mysql://localhost:3306/TestDB” />

       <property name=”username” value=”krian” />

       <property name=”password” value=”kiran123″ />

   </bean>

</beans>

Example of using  JdbcTemplate :

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@Override

   public void save(Employee employee) {

       String query = “insert into Employee (id, name, role) values (?,?,?)”;

    

       JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

    

       Object[] args = new Object[] {employee.getId(), employee.getName(), employee.getRole()};

    

       int out = jdbcTemplate.update(query, args);

    

       if(out !=0){

           System.out.println(“Employee saved with id=”+employee.getId());

       }else System.out.println(“Employee save failed with id=”+employee.getId());

   }

Spring Interview Questions And Answers For Experienced

38. How to use Tomcat JNDI DataSource in a Spring web application?

To use the servlet container configured to use the JNDI DataSource, you must set the appropriate property in the configuration file and then implement it as a dependency. Next, we can use the JdbcTemplate object to perform database operations.

1

2

3

<beans:bean id=”dbDataSource” class=”org.springframework.jndi.JndiObjectFactoryBean”>

   <beans:property name=”jndiName” value=”java:comp/env/jdbc/MyLocalDB”/>

</beans:bean>

39. How can I manage transactions in Spring?

Spring transactions are managed using Declarative Transaction Management (program management). The @Transactional annotation is used to describe the need to manage the transaction. In the configuration file, you need to add the transactionManager setting for the DataSource.

1

2

3

4

<bean id=”transactionManager”

   class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”>

   <property name=”dataSource” ref=”dataSource” />

</bean>

40. Tell us about Spring DAO.

Spring DAO provides the ability to work with data access using technologies like JDBC, Hibernate in a convenient way. There are special classes:  JdbcDaoSupport ,  HibernateDaoSupport ,  JdoDaoSupport ,  JpaDaoSupport .

Spring DAO supports an exception hierarchy, which helps not to handle some exceptions.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

import java.util.List;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class PersonDao extends JdbcDaoSupport{

public void insert(Person person){

String insertSql =”INSERT INTO PERSON (NAME, EMAIL) VALUES(?,?);”;

String name = person.getName();

String email = person.getEmail();

getJdbcTemplate().update(insertSql,new Object[]{name,email});

}

public List<Person> selectAll(){

String selectAllSql = “SELECT * FROM PERSON;”;

return getJdbcTemplate().query(selectAllSql, new PersonRowMapper());

}

}

41. How to integrate Spring and Hibernate?

To integrate Hibernate in Spring, you must enable dependencies, as well as configure the Spring configuration file. Since settings differ slightly between projects and versions, see the official Spring and Hibernate documentation for more specific settings for specific technologies.

42. Tell us about Spring Security.

The Spring Security project provides ample opportunities to protect the application. In addition to the standard settings for authentication, authorization and role distribution and mapping of available pages, links, etc., provides protection against various attack options (for example, CSRF). It has many different settings, but remains easy to use.

43. How to embed java.util.Properties in Spring Bean?

To be able to use Spring EL to embed properties in different bins, you must define a propertyConfigure bean that will load the properties file.

1

2

3

4

5

6

7

 

<bean id=”propertyConfigurer”

 class=”org.springframework.context.support.PropertySourcesPlaceholderConfigurer”>

   <property name=”location” value=”/WEB-INF/application.properties” />

</bean>

<bean class=”com.journaldev.spring.EmployeeDaoImpl”>

   <property name=”maxReadResults” value=”${results.read.max}”/>

</bean>

Or through annotations:

1

2

@Value(“${maxReadResults}”)

private int maxReadResults;

44. What are some of the design patterns used in the Spring Framework?

The Spring Framework uses many design patterns, for example:

  1. Singleton Pattern: Creating beans with default scope.
  2. Factory Pattern: Bean Factory classes
  3. Prototype Pattern: Bean scopes
  4. Adapter Pattern: Spring Web and Spring MVC
  5. Proxy Pattern: Spring Aspect Oriented Programming support
  6. Template Method Pattern: JdbcTemplate, HibernateTemplate etc
  7. Front Controller: Spring MVC DispatcherServlet
  8. Data Access Object: Spring DAO support
  9. Dependency Injection and Aspect Oriented Programming

45. Best Practices in the Spring Framework.

  1. Avoid specifying versions in the namespace to be sure to use the latest versions.
  2. Separate spring configurations according to their activities, for example: spring-jdbc.xml , spring-security.xml .
  3. Spring beans that will be used in different contexts must be specified in the root context and initialized using a listener.
  4. Adjust the dependencies of the bins where possible and avoid automatic linking where there is no strict need.
  5. Create a property file and read it in the Spring configuration file to use application level properties.
  6. For large applications, it is preferable to use settings using xml configuration files, rather than annotations.
  7. Use annotations suitable for the meaning when specifying the bean, for example: @Service for business logic classes and @Repository for classes for working with data.
  8. The spring framework has many modules in the project. Remove any unnecessary dependencies that can be downloaded automatically when specifying the root library.
  9. If you use aspects, make sure you use the attachment point as closely as possible to avoid accidental problems with handling unnecessary methods. Custom annotations can bring significant benefits when using AOP.
  10. Use dependency injection where there is a clear benefit. Deploying dependencies everywhere can add complexity with project support.

RELATED INTERVIEW QUESTIONS

  1. Spring Boot Interview Questions
  2. GIT Interview Questions And Answers
  3. Network Security Interview Questions
  4. CheckPoint Interview Questions
  5. Page Object Model Interview Questions
  6. Apache Pig Interview Questions
  7. Python Interview Questions And Answers
  8. Peoplesoft Integration Broker Interview Questions
  9. PeopleSoft Application Engine Interview Questions
  10. RSA enVision Interview Questions
  11. RSA SecurID Interview Questions
  12. Archer GRC Interview Questions
  13. RSA Archer Interview Questions
  14. Blockchain Interview Questions
  15. Commvault Interview Questions
  16. Peoplesoft Admin Interview Questions
  17. ZooKeeper Interview Questions
  18. Apache Kafka Interview Questions
  19. Couchbase Interview Questions
  20. IBM Bluemix Interview Questions
  21. Cloud Foundry Interview Questions
  22. Maven Interview Questions
  23. VirtualBox Interview Questions
  24. Laravel Interview Questions
  25. Logstash Interview Questions
  26. Elasticsearch Interview Questions
  27. Kibana Interview Questions
  28. JBehave Interview Questions
  29. Openshift Interview Questions
  30. Kubernetes Interview Questions
  31. Nagios Interview Questions
  32. Jenkins Interview Questions
  33. Chef Interview Questions
  34. Puppet Interview Questions
  35. RPA Interview Questions And Answers
  36. Demandware Interview Questions
  37. Visual Studio Interview Questions

Leave a Comment