Spring Interview Questions And Answers Pdf
1. What is Spring?
Answer: 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 Java EE development easier to use and promote good programming practice by enabling a POJO-based programming model.
2. What do you mean by Aspect?
Answer: Aspect is modularization of concern which cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. Aspects are implemented using regular classes or regular classes annotated with the @Aspect annotation in Spring Framework.
3. What are Spring beans?
Answer: The objects that form the backbone of the user’s application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that the users supply to the container.
4. What is a MultipartResolver and when is it used?
Answer: The MultipartResolver interface is used for uploading files. The Spring framework provides one MultipartResolver implementation for use with Commons FileUpload and another for use with Servlet 3.0 multipart request parsing.
Using these, we can support file uploads in our web applications. ( python training online )
5. How would you enable transactions in Spring and what are their benefits?
Answer: There are two distinct ways to configure Transactions – with annotations or by using Aspect-Oriented Programming (AOP) – each with their advantages.
The benefits of using Spring Transactions, according to the official docs, are:
Provide a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO
Support declarative transaction management
Provide a simpler API for programmatic transaction management than some complex transaction APIs such as JTA
Integrate very well with Spring’s various data access abstractions.
6. How do we implement DI in Spring Framework?
Answer: We can use Spring XML based as well as Annotation-based configuration to implement DI in spring applications. For better understanding, please read Spring Dependency Injection example where you can learn both the ways with JUnit test case. The post also contains a sample project zip file, that you can download and play around to learn more.
7. What are the features of Spring?
Answer:
Lightweight:
Spring is lightweight when it comes to size and transparency. The basic version of the spring framework is around 1MB. And the processing overhead is also very negligible.
Inversion of control (IOC):
Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
Aspect-oriented (AOP):
Spring supports Aspect-oriented programming and enables cohesive development by separating application business logic from system services.
Container:
Spring contains and manages the life cycle and configuration of application objects.
MVC Framework:
Spring comes with an MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
JDBC Exception Handling:
The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO, and iBATIS.
Transaction Management:
Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring’s transaction support is not tied to J2EE environments and it can be also used in container fewer environments.
8. Describe the Spring Framework?
Answer: The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications – on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the “plumbing” of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.
9. What are the benefits of using Spring Tool Suite?
Answer: We can install plugins into Eclipse to get all the features of Spring Tool Suite. However, STS comes with Eclipse with some other important 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. ( puppet training )
10. Name some of the important Spring Modules?
Answer:
Some of the important Spring Framework modules are:
Spring Context – for dependency injection.
Spring AOP – for aspect-oriented programming.
Spring DAO – for database operations using DAO pattern
Spring JDBC – for JDBC and DataSource support.
Spring ORM – for ORM tools support such as Hibernate
Spring Web Module – for creating web applications.
Spring MVC – Model-View-Controller implementation for creating web applications, web services, etc.
11. What is Aspect-Oriented Programming?
Answer: Aspects enable the modularization of crosscutting concerns such as transaction management that span multiple types and objects by adding extra behavior to already existing code without modifying affected classes.
12. What is Weaving?
Answer: According to the official docs, weaving is a process that links aspects with other application types or objects to create an advised object. This can be done at compile-time, load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.
13. What is a Spring Framework?
Answer: Spring logo – Spring Interview Questions – Edureka!Spring is a powerful open source, application framework created to reduce the complexity of enterprise application development. It is light-weighted and loosely coupled. It has layered architecture, which allows you to select the components to use, while also providing a cohesive framework for J2EE application development. Spring framework is also called a framework of frameworks as it provides support to various other frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc.
14. What are Aspect, Advice, Pointcut, and JoinPoint in AOP?
Answer: Aspect: a class that implements cross-cutting concerns, such as transaction management
Advice: the methods that get executed when a specific JoinPoint with matching Pointcut is reached in the application
Pointcut: a set of regular expressions that are matched with JoinPoint to determine whether Advice needs to be executed or not
JoinPoint: a point during the execution of a program, such as the execution of a method or the handling of an exception.
15. How to get ServletContext and ServletConfig object in a Spring Bean?
Answer: 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, please read Spring Aware Interfaces
Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in the servlet container specific environment only though.
@Autowired
ServletContext servlet context;
16. Name the exceptions thrown by the Spring DAO classes?
Answer: See the below diagram, it depicts all the Spring DAO classes in the hierarchical order.
17. What are the different types of Spring Bean auto wiring?
Answer:
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, auto-wire by autodetecting was also supported that was similar to the auto-wire by constructor or byType. For more details about these options, please read Spring Bean Autowiring.
18. What are Bean wiring and @Autowired annotation?
Answer: The process of injection spring bean dependencies while initializing it called Spring Bean Wiring.
Usually, it’s best practice to do the explicit wiring of all the bean dependencies, but the spring framework also supports auto wiring. We can use @Autowired annotation with fields or methods for autowiring byType. For this annotation to work, we also need to enable annotation-based configuration in spring bean configuration file. This can be done by context:annotation-config element.
19. Describe Spring DAO support?
Answer: The Data Access Object (DAO) support in Spring makes it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies easily. It also allows you to code without worrying about catching exceptions that are specific to each of this technology.
20. Which classes are present in spring JDBC API?
Answer:
Classes present in JDBC API are as follows:
JdbcTemplate
SimpleJdbcTemplate
NamedParameterJdbcTemplate
SimpleJdbcInsert
SimpleJdbcCall
21. How do you turn on annotation wiring?
Answer: Annotation wiring is not turned on in the Spring container by default. In order to use annotation-based wiring, we must enable it in our Spring configuration file by configuring element.
22. What do you understand by @Required annotation?
Answer: @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 explicit property value in a bean definition or with auto wiring. If the affected bean property has not been populated, the container will throw BeanInitializationException.
For example:
public class Employeea
{private String name;
@Required
public void setName(String name)
{this.name=name; }
public string getName()
{ return name; }
23. How to handle exceptions in Spring MVC Framework?
Answer: Spring MVC Framework provides the following ways to help us achieving robust exception handling.
Controller-Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides a HandlerExceptionResolver interface that we can implement to create a global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.
For a complete example, please read the Spring Exception Handling Example.
24. What is a Proxy?
Answer: A proxy is an object that is created after applying the advice to a target object. When you think of client objects the target object and the proxy object are the same.
25. What is Spring Security?
Answer: Spring security framework focuses on providing both authentication and authorization in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attack.
It’s very beneficial and easy to use Spring security in web applications, through the use of annotations such as @EnableWebSecurity. You should go through the following posts to learn how to use the Spring Security framework.
Spring Security in Servlet Web Application
Spring MVC and Spring Security Integration Example
26. How to inject a java.util.Properties into a Spring Bean?
Answer: We need to define propertyConfigurer bean that will load the properties from the given property file. Then we can use Spring EL support to inject properties into other bean dependencies. For example;
If you are using annotation to configure the spring bean, then you can inject property like below.
27. What is a MultipartResolver and when it’s used?
Answer: 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 “multipart resolver” 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. For a complete example, please read Spring MVC File Upload Example.
28. Name the types of transaction management that Spring supports?
Answer:
Two types of transaction management are supported by Spring. They are:
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.
Declarative transaction management: In this, transaction management is separated from the business code. Only annotations or XML based configurations are used to manage the transactions.
29. What are the ways by which Hibernate can be accessed using Spring?
Answer:
There are two ways by which we can access Hibernate using Spring:
Inversion of Control with a Hibernate Template and Callback
Extending HibernateDAOSupport and Applying an AOP Interceptor node.
30. What is Spring MVC framework?
Answer: Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC framework uses IoC to provide a clean separation of controller logic from business objects. It also allows to declaratively bind request parameters to business objects.
31. How to create ApplicationContext in a Java Program?
Answer: There are following ways to create spring context in a standalone java program.
AnnotationConfigApplicationContext: If we are using Spring in standalone Java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.
ClassPathXmlApplicationContext: If we have spring bean configuration XML file in a standalone application, then we can use this class to load the file and get the container object.
FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
32. What are the minimum configurations needed to create a Spring MVC application?
Answer: For creating a simple Spring MVC application, we would need to do the following tasks.
Add spring-context and spring-web MVC dependencies in the project.
Configure DispatcherServlet in the web.xml file to handle requests through spring container.
Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also, we need to configure view resolver for view pages.
Controller class with request mappings defined to handle the client requests.
Above steps should be enough to create a simple Spring MVC Hello World application.
33. How can you inject a Java Collection in Spring?
Answer: Spring offers the following types of collection configuration elements:
The type is used for injecting a list of values, in the case that duplicates are allowed.
The type is used for wiring a set of values but without any duplicates.
The
type is used to inject a collection of name-value pairs where name and value can be of any type.
The type can be used to inject a collection of name-value pairs where the name and value are both Strings. (
34. What is Controller in Spring MVC framework?
Answer: Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.
35. Explain annotation-based (@AspectJ based) aspect implementation?
Answer: This implementation case (@AspectJ based implementation) refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.
36. What are the different types of AutoProxying?
Answer:
BeanNameAutoProxyCreator
DefaultAdvisorAutoProxyCreator
Metadata autoproxying
37. Explain XML Schema-based aspect implementation ?
Answer: In this implementation case, aspects are implemented using regular classes along with XML based configuration.
38. How would you relate the Spring MVC Framework to MVC architecture?
Answer: As the name suggests Spring MVC is built on top of Model-View-Controller architecture. DispatcherServlet is the Front Controller in the Spring MVC application that takes care of all the incoming requests and delegates it to different controller handler methods.
The model can be any Java Bean in the Spring Framework, just like any other MVC framework Spring provides automatic binding of form data to java beans. We can set model beans as attributes to be used in the view pages.
View Pages can be JSP, static HTML, etc. and view resolvers are responsible for finding the correct view page. Once the view page is identified, control is given back to the DispatcherServlet controller. DispatcherServlet is responsible for rendering the view and returning the final response to the client.
39. How to achieve localization in Spring MVC applications?
Answer: Spring provides excellent support for localization or i18n through resource bundles. Basis steps needed to make our application localized are:
Creating message resource bundles for different locales, such as messages_en.properties, messages_fr.properties, etc.
Defining message source bean in the spring bean configuration file of type ResourceBundleMessageSource or ReloadableResourceBundleMessageSource.
For a change of locale support, define locale resolver bean of type CookieLocaleResolver and configure LocaleChangeInterceptor interceptor. An example configuration can be like below:
Use spring: message element in the view pages with key names, DispatcherServlet picks the corresponding value and renders the page in the corresponding locale and return a response.
For a complete example, please read the Spring Localization Example.
40. What are some of the important Spring annotations you have used?
Answer:
Some of the Spring annotations that I have used in my project are:
Controller – for controller classes in Spring MVC project.
RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples
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 auto wiring dependencies in spring beans.
Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type are 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.
Can we send an Object as the response of Controller handler method?
Yes, we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.
41. What are the major features in different versions of Spring?
Answer:
Some of the Spring annotations that I have used in my project are:
@Controller – for controller classes in Spring MVC project.
@RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples
@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 are 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.
42. What’s the Difference Between @Controller, @Component, @Repository, and @Service Annotations in Spring?
Answer: According to the official Spring documentation, @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.
Let’s take a look at specific use cases of the last three:
@Controller – indicates that the class serves the role of a controller, and detects @RequestMapping annotations within the class
@Service – indicates that the class holds business logic and calls methods in the repository layer
@Repository – indicates that the class defines a data repository; its job is to catch platform-specific exceptions and re-throw them as one of Spring’s unified unchecked exceptions.
43. How to validate if the bean was initialized using valid values?
Answer: Spring supports JSR-303 annotation-based validations. JSR-303 is a specification of the Java API for bean validation, part of JavaEE and JavaSE, which ensures that properties of a bean meet specific criteria, using annotations such as @NotNull, @Min, and @Max. The article regarding JSR-303 is available here.
What’s more, Spring provides the Validator interface for creating custom validators. For example, you can have a look here.
44. List the advantages of Spring Framework?
Answer: Because of Spring Frameworks layered architecture, you can use what you need and leave which you don’t.
Spring Framework enables POJO (Plain Old Java Object) Programming which in turn enables continuous integration and testability.
JDBC is simplified due to Dependency Injection and Inversion of Control.
It is open-source and has no vendor lock-in.
45. What are the different features of the Spring Framework?
Answer:
Following are some of the major features of the Spring Framework :
Lightweight: Spring is lightweight when it comes to size and transparency.
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.
Container: Spring Framework creates and manages the life cycle and configuration of the application objects.
MVC Framework: Spring Framework’s MVC web application framework is highly configurable. Other frameworks can also be used easily instead of Spring MVC Framework.
Transaction Management: Generic abstraction layer for transaction management is provided by the Spring Framework. Spring’s transaction support can be also used in container fewer environments.
JDBC Exception Handling: The JDBC abstraction layer of the Spring offers an exception hierarchy, which simplifies the error handling strategy.
46. What does a Spring Bean definition contain?
Answer:
A Spring Bean definition contains all configuration metadata which is needed for the container to know how to create a bean, its lifecycle details, and its dependencies. ( oracle apex training online )
47. How do you define the scope of a bean?
Answer:
When defining an in Spring, we can also declare a scope for the bean. It can be defined through the scope attribute in the bean definition. For example, when Spring has to produce a new bean instance each time one is needed, the bean’s scope attribute to be a prototype. On the other hand, when the same instance of a bean must be returned by Spring every time it is needed, the bean scope attribute must be set to a singleton.
48. What are some of the important features and advantages of Spring Framework?
Answer: Spring Framework is built on top of two design concepts – Dependency Injection and Aspect-Oriented Programming.
Some of the features of spring framework are:
Lightweight and very little overhead of using a framework for our development.
Dependency Injection or Inversion of Control to write components that are independent of each other, spring container takes care of wiring them together to achieve our work.
Spring IoC container manages Spring Bean life cycle and project-specific configurations such as JNDI lookup.
Spring MVC framework can be used to create web applications as well as restful web services capable of returning XML as well as JSON response.
Support for transaction management, JDBC operations, File uploading, Exception Handling, etc with very little configurations, either by using annotations or by spring bean configuration file.
Some of the advantages of using Spring Framework are:
Reducing direct dependencies between different components of the application, usually Spring IoC container is responsible for initializing resources or beans and inject them as dependencies.
Writing unit test cases are easy in Spring framework because our business logic doesn’t have direct dependencies with actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing purposes.
Reduces the amount of boiler-plate code, such as initializing objects, open/close resources. I like JdbcTemplate class a lot because it helps us in removing all the boiler-plate code that comes with JDBC programming.
Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we don’t need Spring transaction management features, we don’t need to add that dependency in our project.
Spring framework supports most of the Java EE features and even much more. It’s always on top of the new technologies, for example, there is a Spring project for Android to help us write better code for native android applications. This makes spring framework a complete package and we don’t need to look after the different framework for different requirements.
49. Explain Bean lifecycle in Spring framework?
Answer:
Following is a 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 bean factory to setBeanFactory() method.
Pre Initialization: Also called the post process of the 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 an 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 Disposable Bean, it will call the destroy() method. ( hadoop training videos )
50. What is the Spring Java Based Configuration?
Answer: Java-based configuration option enables the user to write most of their Spring configuration without XML but with the help of few Java-based annotations.
for example:
Annotation @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions. The @Bean annotation tells spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.
51. Describe some of the standard Spring events?
Answer:
Spring provides the following standard events:
ContextRefreshedEvent: This event is published when the ApplicationContext is either initialized or refreshed. This can also be raised using the refresh() method on the ConfigurableApplicationContext interface.
ContextStartedEvent: This event is published when the ApplicationContext is started using the start() method on the ConfigurableApplicationContext interface. the user can poll their database or they can re/start any stopped application after receiving this event.
ContextStoppedEvent: This event is published when the ApplicationContext is stopped using the stop() method on the ConfigurableApplicationContext interface. the users can do required housekeep work after receiving this event.
ContextClosedEvent: This event is published when the ApplicationContext is closed using the close() method on the ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be refreshed or restarted.
RequestHandledEvent: This is a web-specific event telling all beans that an HTTP request has been serviced. ( data science online training )
52. What are the types of Dependency Injection Spring supports?
Answer:
Setter Injection
Setter-based DI is realized by calling setter methods on the user’s beans after invoking a no-argument constructor or no-argument static factory method to instantiate their bean.
Constructor Injection
Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.
53. What is the Spring Bean life cycle?
Answer:
Spring Beans are initialized by Spring Container and all the dependencies are also injected. When the context is destroyed, it also destroys all the initialized beans. This works well in most of the cases but sometimes we want to initialize other resources or do some validation before making our beans ready to use. Spring framework provides support for post-initialization and pre-destroy methods in spring beans.
We can do this in two ways – by implementing InitializingBean and DisposableBean interfaces or using init-method and destroy-method attribute in spring bean configurations. For more details, please read Spring Bean Life Cycle Methods.
Note: Browse latest Spring Interview Questions and Spring Tutorial Videos. Here you can check Spring Training details and Spring Training Videos for self learning. Contact +91 988 502 2027 for more information.