Here we have mentioned most frequently asked Spring Interview Questions and Answers specially for freshers and experienced.


 

1. What is a spring?

Ans:

Spring is set to be a framework which helps Java programmer for development of code and it provides IOC container, Dependency Injector, MVC flow and many other APIs for the java programmer.

2. What are Advices in Spring?

Ans:

It is the execution of an aspect. Advice is like making your application learn a new trick. They are usually introduced at joinpoints.

3. What is the default scope of bean in Spring framework?

Ans:

The default scope of bean is Singleton for Spring framework.

4. Name the types of transaction management that are supported by Spring?

Ans:

Transaction management supported by Spring are :
Declarative transaction management.
Programmatic transaction management.

5. Is Singleton beans are thread safe in Spring Framework?

Ans:

No, singleton beans are not thread-safe in Spring framework.

6. What are the benefits of Spring Framework?

Ans:

Following are the benefits of Spring framework:
Extensive usage of Components
Reusability
Decoupling
Reduces coding effort by using pattern implementations such as singleton, factory, service locator etc.
Removal of leaking connections
Declarative transaction management
Easy to integrate with third party tools and technologies.

7. What is Bean Factory?

Ans:

Bean Factory is core of the spring framework and, it is a Lightweight container which loads bean definitions and manages your beans. Beans are configured using XML file and manage singleton defined bean. It is also responsible for life cycle methods and injects dependencies. It also removes adhoc singletons and factories.

8. Define Bean Wiring?

Ans:

Bean wiring is the creation of associations between application components that are between the beans in a particular spring container.

9. What is called Spring MVC?

Ans:

A Spring MVC is a single shared controller instance and it is used to handle request type controllers, interceptors which run in the IoC container. It also allows multiple Dispatcher Servlets which can share application context interface but not class based interface.

10. Why Spring framework is needed?

Ans:

Spring framework is needed because it is –
Very Light Weight Container
Framework
IOC
AOP



 

11. Name the various modules used in spring framework?

Ans:

AOP module (Aspect Oriented Programming)
JDBC abstraction and DAO module
The Core container module
MVC framework module
Application context module
O/R mapping integration module (Object/Relational)
Web module

12. Explain the RowCallbackHandler in Spring?

Ans:

The RowCallbackHandler is called for each row in ResultSet and is used to read values from the ResultSet.

13. Define Application context module?

Ans:

This is a very important module and supplies various necessary services like EJB integration, remoting, JNDI access and scheduling. It transforms spring into a framework. It also broadens the idea of BeanFactory by application of lifecycle events, providing support for internationalization messages and validation.

14. Write about AOP module?

Ans:

AOP module is utilized for creating aspects for Spring applications. It also enables support for metadata programming in Spring.

15. What is a BeanFactory Interface?

Ans:

Bean factory interface is used to provide configuration framework for object creation and basic functionality around object management.

16. State the differences between ApplicationContext and BeanFactory in spring?

Ans:

ApplicationContext allows more than one config files to exist while BeanFactory only permits one.
ApplicationContext can print events to beans registered as listeners. This feature is not supported by BeanFactory.
ApplicationContext also provides support for application of lifecycle events, internationalization messages and validation and also provides services like EJB integration, remoting, JNDI access and scheduling. These features too are not supported by Bean Factory.

17. What is Auto Wiring?

Ans:

Autowiring is used to build relationships between the collaborating beans. Spring container can automatically resolve collaborators for beans.

18. What are the different Modes of Autowiring?

Ans:

Autowiring has five different modes:
no: no autowire
byName : Autowiring that can be done by property name
byType : property type as autowired
constructor: It is similar to byType and it is property is in constructor
autodetect : Spring is allowed to select autowiring from byType or constructor

19. How to start using spring?

Ans:

Following steps needs to be done to start with the Spring:
Download Spring and its dependent file from spring’s site.
Create application context xml to define beans and its dependencies
Integrate application context xml with web.xml
Deploy and Run the application

20. What are the methods of bean life cycle?

Ans:

There are two important methods of Bean life cycle:
Setup – called when bean is loaded into container
Teardown – called when bean is unloaded into container




 

21. What are the different types of events of Listeners?

Ans:

Following are the different types of events of listeners:
ContextClosedEvent – This event is called when the context is closed.
ContextRefreshedEvent – This event is called when context is initialized or refreshed
RequestHandledEvent – This event is called when the web context handles request

22. Differentiate between singleton and prototype bean?

Ans:

Singleton means only one bean is defined per object instance while Prototype means one definition to more than one object instances in Spring.

23. What are the types of Dependency Injection?

Ans:

Two types of dependency injection are supported by spring framework:
Setter Injection
Constructor Injection

24. Write about Core container module?

Ans:

Core container module is responsible for the basic functionality of the spring framework. The whole Spring framework is built with this module as a base.

25. What is AOP module?

Ans:

This AOP module is used for spring enabled application. Support has been provided AOP alliance to ensure the interoperability between spring and other AOP frameworks.It instructs spring to add annotations to the source code and tell how to apply aspects.

26. What is AOP Alliance?

Ans:

AOP alliance is an open-source project which is aimed at promoting adoption of AOP. The AOP alliance’s goal is to define a common set of components and interfaces so as to improve interoperability among different AOP implementations.

27. What is called spring configuration file?

Ans:

Spring configuration file is an XML file and it contains class information. It also describes how these classes are configured and interact with each other.

28. What are different types of Autowire?

Ans:

There are four different types of Auto wire:
byName
byType
constructor
autodetect

29. What are the types of the transaction management that is supported by spring?

Ans:

Following are the types of transaction management that has been supported by spring:
declarative
programmatically

30. When are declarative and programmatic transaction management used?

Ans:

When only a small amount of transactional operations is there, it is advised to use Programmatic transaction management. But if there is a big amount of transactional operations to be taken care of, declarative transaction management is preferred.


 

31. What is IOC?

Ans:

IOC (Inversion of Control pattern) is also known as dependency injection. IOC directs the programmers to depict how to create objects instead of actually creating them. But in this design pattern, this control has been given to assembler and assembler will instantiate required class if needed.

32. Write about the different types of Listener related events?

Ans:

The different types of events related to listeners are:
ContextRefreshedEvent – This gets called when the context is refreshed or initialized.
RequestHandledEvent – This gets called when the web context is handling a request.
ContextClosedEvent – This gets called when the context gets closed.

33. What is an Aspect?

Ans:

Aspect is also called as logging which is required throughout the application. Logging or aspect is a cross cutting functionality in an application using AOP.

34. What is a Joinpoint?

Ans:

The point where an aspect can be introduced in the application is known as a joinpoint. This point could be a field being modified, a method being called or even an exception being thrown. At these points, the new aspect’s code can be added to introduce a new behavior to the application.
Aspect code can be inserted at this point into normal flow of application to change the current behavior.

35. What is called an Advice?

Ans:

Advice will tell application on new behavior and it is the implementation of an aspect. It is inserted into an application at the joinpoint.
Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, the advice is inserted into an application at joinpoints.

36. What is a Pointcut?

Ans:

Pointcut is used to allow where the advice can be applied.

37. What is weaving?

Ans:

Weaving is used to create new proxy object by applying aspects to target object.

38. What is difference between singleton and prototype bean?

Ans:

Singleton Bean – Single bean definition to a single object instance per Spring IOC container
Prototype Bean – Single bean definition to any number of object instances per Spring IOC Container

39. In what points, can weaving be applied?

Ans:

Following are the points where weaving can be applied:
Compile Time
Class load Time
Runtime

40. What are the different types of AutoProxying?

Ans:

Following are the different types of AutoProxying:
BeanNameAutoProxyCreator
DefaultAdvisorAutoProxyCreator
Metadata autoproxying



 

41. How can beans be made singleton or prototype?

Ans:

The bean tag has an attribute called ‘singleton’. The bean is singleton if its value is ‘TRUE’, otherwise the bean is a prototype.

42. What classes are used to Control the database connection?

Ans:

Following are the classes that are used to control database connection:
Data Source Utils
SmartData Source
AbstractData Source
SingleConnection DataSource
DriverManager DataSource
TransactionAware DataSourceProxy
DataSource TransactionManager

43. Describe about DAO in Spring framework?

Ans:

DAO is used to provide integration of Java database connectivity and Object relational mapping objects. DAO is spring framework provides connection for JDBC, hibernate, JDO, JPA, Common client interface and Oracle.

44. What is Autoproxying?

Ans:

Autoproxying is used to create proxy automatically for the spring users. It provides following two classes to support this automatic proxy creation:
BeanNameAutoProxyCreator
DefaultAdvisorAutoProxyCreator

45. What is Metadata Autoproxying?

Ans:

Metadata Autoproxying can be performed inspiring which can be driven by metadata. This is determined by source level attributes and keeps metadata inside the source code.
This maintains metadata in one place and mainly used for declarative transaction support.

46. What is ‘Throws advice’ in Spring?

Ans:

‘Throws Advice’ define the behavior when an exception occurs. It is an interface and it has no methods which need to be implemented.
A class that implements this interface should have method with this signature:
Void samplethrow (Throw table t)
Void samplethrow(Method m, Object[] o, Object target, Throw tablet)

47. What are the various editors used in spring work?

Ans:

The various custom editors provided by the Spring Framework are:
PropertyEditor
URLEditor
ClassEditor
CustomDateEditor
FileEditor
LocaleEditor
StringArrayPropertyEditor
StringTrimmerEditor

48. What are the advantages of spring framework?

Ans:

Following are the advantages of spring framework:
Layered Architecture
Enables Plain Old Java Object (POJO) Programming and it enables continuous integration and testability
Dependency Injection and Inversion of Control that simplifies JDBC
Open source framework which can be used for commercial purpose

49. How is Hibernate accessed using the Spring framework?

Ans:

Hibernate can be accessed in the following two ways:
By IOC with a Callback and HibernateTemplate.
By applying an AOP Interceptor and broadening the HibernateDaoSupport.

50. What are the various Channels supported by Spring 2.0?

Ans:

Following are the channels supported by spring version 2.0:
Pollable Channel
Subscribable Channel
PublishSubscribe Channel
Queue Channel
Priority Channel
Rendezvous Channel
Direct Channel
Executor Channel
Scoped Channel




 

51. Why is declarative transaction management preferred in Spring?

Ans:

Declarative transaction management has minimum impact on the application code and, therefore, is an idealistic lightweight container.

52. Explain the concept of a BeanFactory?

Ans:

BeanFactory applies the idea of a factory pattern that utilizes IOC to separate the application’s dependencies and configuration from the actual code.

53. What are the different scopes of spring bean?

Ans:

Scopes of spring bean are Singleton, prototype, request, session and global session.

54. What are all the ways to access Hibernate by using Spring?

Ans:

There are two ways to access hibernate using spring:
Inversion of Control with a Hibernate Template and Callback
Extending HibernateDAOSupport and Applying an AOP Interceptor node.

55. How struts application can be integrated with spring?

Ans:

There are two options for struts application that can be integrated with spring:
Configuration of Spring to manage beans using ContextLoader plugin and set their dependencies in a spring context file
Grab spring managed beans explicitly using agetwebapplicationcontext()

56. What is Inversion of control (IOC)?

Ans:

Inversion of Control (IOC) is also called as dependency Injection which is nothingbut a design pattern that gives control to the assembler of classes. In general, class will instantiate another class if required.
But in this design pattern, this control has been to given to assembler and assembler will instantiate required class if needed.

57. Write the benefits of using IOC?

Ans:

The major benefits of dependency injection or IOC are that it reduces the amount of coding required for the application. This allows the testing of the application to be done quickly and easily as no JNDI lookup mechanism or singletons are required. IOC containers also support lazy loading and eager installation of services.

58. What is Inner bean? What is the drawback of inner bean?

Ans:

If a bean element is directly embedded in a property tag while wiring beans, then the bean is called Inner Bean. Its drawback is that it cannot be reprocessed.

59. What are the different types of Injection in spring?

Ans:

There are three types of Injection in spring:
Setter Injection
Constructor Injection
Getter or Method Injection

60. What are the benefits of spring framework?

Ans:

Following are the benefits of spring framework:
Light weight container when compared to j2EE containers
Built in Web MVC framework
Creates loosely coupled applications
Supports aspect oriented programming like logging, transaction and security
Configuration done in XML format which is easy to write and understand


 

61. What are the types of Advice?

Ans:

There are five types of Advice:
Before Advice
After returning advice
After throwing advice
Finally advice
Around advice

62. What is called PreparedStatementCreator?

Ans:

PreparedStatementCreator is one of the most commonly used interfaces for writing data to the database. createPreparedStatement() is a method that can be used to create and return PreparedStatement from the Connection argument, and exception handling is automatically taken care of. When this interface is implemented, a different interface SqlProvider can also be implemented which has a method called getSql(). This method is useful for providing sql strings to the JdbcTemplate. It does not handle SQLExceptions.

63. What is SQLProvider?

Ans:

SQLProvider has only one method called getSql()and it is implemented using PreparedStatementCreator implementers. It is mainly used for debugging.

64. Write about BatchPreparedStatementSetter?

Ans:

BatchPreparedStatementSetter is used to update more than a single row in one go, they can use BatchPreparedStatementSetter. This interface provides two methods they are
setValues( PreparedStatement ps, int i) throws SOL exception
int getBatchSize

65. What is the better method of using JDBC in Spring?

Ans:

If JDBC is used with the template class called JdbcTemplate, it gives a better performance.

66. What exceptions do the DAO classes, use in Spring throw?

Ans:

In spring DAO classes only throws SQLException.

67. Explain the advantages of using DAO module?

Ans:

The database code can be kept clean and simple by using the DAO module. This helps in preventing problems that rise because of poor handling of closures of database resources. Also, the DAO module utilizes the AOP module to enable objects in the Spring application to use transaction management services.

68. Name the significant ApplicationContext implementations used in the spring framework?

Ans:

They are:
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
XmlWebApplicationContext

69. How is a bean added to a Spring application?

Ans:

The bean tag has an ID attribute which stores the bean name and a class attributes which specifies the full class name.

70. What are ORM integration modules?

Ans:

Object/relational mapping (ORM) tool is supported by Spring over straight JDBC by implementing the ORM module. Spring can join various important ORM frameworks, including JDO, iBATIS SQL Maps and Hibernate.



 

71. Mention and explain the types of Advice in Spring?

Ans:

Types of advice are:
Before advice: Advice that is executed prior to a joinpoint is called the ‘before advice’.
After returning advice: Advice that is executed after the normal completion of a joinpoint is called the ‘after returning advice’.
After throwing advice: Advice that is executed only if a method exits abnormally by throwing an exception, is called the ‘after throwing advice’.
After (finally) advice: Advice that is executed irrespective of how a joinpoint exits is called ‘after finally advice’.
Around advice: Advice that borders a joinpoint, for example, a method invocation, is called an ‘around advice’. This can be used to perform special activities before and after the invocation of method.

72. What is the web module?

Ans:

The web module enables the creation of a web application without XML. The web.xml file needs to be configured for using the web module.

73. What is DataAccessException?

Ans:

DataAccessException is a RuntimeException. It is an Unchecked Exception. The user cannot be forced to handle these kinds of exceptions.

74. What is XMLBeanFactory?

Ans:

Spring includes several applications of Bean factory. Out of these, org.springframework.beans.factory.xml.XmlBeanFactory is a very important one. It loads the beans on the basis of the definitions stored in an XML file. For the creation of an XmlBeanFactory, a java.io.InputStream is passed to the constructor. The InputStream provides the XML to the factory. For example, for retrieval of the bean, the getBean() method is called by passing the name of the desired bean.

MyBean helloBean = (MyBean) factory.getBean("helloBean");

75. Name the Exception class which is connected to the exceptions thrown by the applications?

Ans:

It is the DataAccessException given by org.springframework.dao.DataAccessException

76. Mention the types of lOC (dependency injection)?

Ans:

The different types of loC are: –
Setter Injection: With the help of JavaBeans properties.
Constructor Injection: Dependencies are given in the form of constructor parameters.
Interface Injection: With the help of an interface, an Injection is performed.
Out of these three, only construction and setter are being used in Spring.

77. What are the important beans lifecycle methods?

Ans:

All in all, two bean lifecycle methods are there. The first method is the setup method which is called during the loading of the bean into the container. The second is when the bean is unloaded from the container, and this method is called the teardown.

78. How can the default lifecycle methods of beans be nullified?

Ans:

The tag, bean, has two useful attributes which can be used to define special initialization and destruction methods.
For Example, two new methods forSetup and forTeardown can be added to the Foo class in the following way:



79. What is a Target?

Ans:

A target is the class that is advised. This class can either be a class to which we want to add a special behavior to or a third party class. The target class is free to center on its major concern using the AOP concepts, regardless of any advice that is being applied.

80. Explain the term Proxy?

Ans:

The term proxy refers to an object which is produced the application of an advice to the target object.




 

81. What is cross cutting concern and concern in spring AOP?

Ans:

Cross cutting concern: It is a concern which is applicable throughout the application and it affects the entire application. E.g Security, logging and data transfer are the concerns which are needed in almost every module of an application.
Concern: Concern is a behavior that we want to have in a module of an application. Issues in which we are interested defines our concern.

82. What are different Modes of auto wiring?

Ans:

The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection –
no – This is default setting which means no autowiring and you should use explicit bean reference for wiring. You have nothing to do special for this wiring. This is what you already have seen in Dependency Injection chapter.
byName – Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
byType – Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.
constructor – Similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
autodetect – Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

83. What is WebApplicationContext ?

Ans:

The WebApplicationContext is an extension of the plain ApplicationContextthat has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with.

84. What is Annotation-based container configuration?

Ans:

An alternative to XML setups is provided by annotation-based configuration which relies on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

85. What does @Required annotation mean?

Ans:

This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected bean property has not been populated.

86. What does @Autowired annotation mean?

Ans:

This annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.

87. What does @Qualifier annotation mean?

Ans:

There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.

88. What are the JSR-250 Annotations? Explain them.

Ans:

Spring has JSR-250 based annotations which include @PostConstruct, @PreDestroy and @Resource annotations.
@PostConstruct – This annotation can be used as an alternate of initialization callback.
@PreDestroy – This annotation can be used as an alternate of destruction callback.
@Resource – This annotation can be used on fields or setter methods. The @Resource annotation takes a ‘name’ attribute which will be interpreted as the bean name to be injected. You can say, it follows by-name autowiring semantics.

89. What is Spring Java Based Configuration? Give some annotation example.

Ans:

Java based configuration option enables you to write most of your 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 @Beanannotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.

90. How is event handling done in Spring?

Ans:

Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.


 

91. Describe some of the standard Spring events.

Ans:

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. You can poll your database or you 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. You 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.

92. What is Aspect?

Ans:

A module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style).

93. What is the difference between concern and cross-cutting concern in Spring AOP?

Ans:

Concern – Concern is behavior which we want to have in a module of an application. Concern may be defined as a functionality we want to implement. Issues in which we are interested define our concerns.
Cross-cutting concern – It’s a concern which is applicable throughout the application and it affects the entire application. e.g. logging , security and data transfer are the concerns which are needed in almost every module of an application, hence are cross-cutting concerns.

94. What is Join point?

Ans:

This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.

95. What is Advice?

Ans:

This is the actual action to be taken either before or after the method execution. This is actual piece of code that is invoked during program execution by Spring AOP framework.

96. What is Pointcut?

Ans:

This is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples.

97. What is Introduction?

Ans:

An introduction allows you to add new methods or attributes to existing classes.

98. What is Target object?

Ans:

The object being advised by one or more aspects, this object will always be a proxy object. Also referred to as the advised object.

99. What is Weaving?

Ans:

Weaving is the process of linking aspects with other application types or objects to create an advised object.

100. What are the different points where weaving can be applied?

Ans:

Weaving can be done at compile time, load time, or at runtime.



 

101. What is Spring Framework?

Ans:

Spring is one of the most widely used Java EE framework. Spring framework core concepts are “Dependency Injection” and “Aspect Oriented Programming”.
Spring framework can be used in normal java applications also to achieve loose coupling between different components by implementing dependency injection and we can perform cross cutting tasks such as logging and authentication using spring support for aspect oriented programming.
I like spring because it provides a lot of features and different modules for specific tasks such as Spring MVC and Spring JDBC. Since it’s an open source framework with a lot of online resources and active community members, working with Spring framework is easy and fun at same time.

102. What are some of the important features and advantages of Spring Framework?

Ans:

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 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 support 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 different framework for different requirements.

103. What do you understand by Dependency Injection?

Ans:

Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement dependency injection pattern to move the dependency resolution from compile-time to runtime.
Some of the benefits of using Dependency Injection are: Separation of Concerns, Boilerplate Code reduction, Configurable components and easy unit testing.
Read more at Dependency Injection Tutorial. We can also use Google Guice for Dependency Injectionto automate the process of dependency injection. But in most of the cases we are looking for more than just dependency injection and that’s why Spring is the top choice for this.

104. How do we implement DI in Spring Framework?

Ans:

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 sample project zip file, that you can download and play around to learn more.

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

Ans:

We can install plugins into Eclipse to get all the features of Spring Tool Suite. However STS comes with Eclipse with some other important stuffs 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 advices, 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.

106. Name some of the important Spring Modules?

Ans:

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.

107. What do you understand by Aspect Oriented Programming?

Ans:

Enterprise applications have some common cross-cutting concerns that is applicable for different types of Objects and application modules, such as logging, transaction management, data validation, authentication etc. In Object Oriented Programming, modularity of application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and they are configured to cut across different classes methods.
AOP takes out the direct dependency of cross-cutting tasks from classes that is not possible in normal object oriented programming. For example, we can have a separate class for logging but again the classes will have to call these methods for logging the data. Read more about Spring AOP support at Spring AOP Example.

108. What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?

Ans:

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 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 gets executed when a specific join point with matching pointcut is reached in the application. You can think of Advices as Spring interceptors or Servlet Filters.
Pointcut: Pointcut are regular expressions that is 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 the specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join points is always the execution of a method.
Advice Arguments: We can pass arguments in the advice methods. We can use 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 argument type is determined.
These concepts seems confusing at first, but if you go through Spring Aspect, Advice Example then you can easily relate to them.

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

Ans:

AspectJ is the industry-standard implementation for Aspect Oriented Programming whereas Spring implements AOP for some cases. Main differences between Spring AOP and AspectJ are:
· Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.
· Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.
· Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ support all kinds of pointcuts.
· One of the shortcoming of Spring AOP is that it can be applied only to the beans created through Spring Context.

110. What is Spring IoC Container?

Ans:

Inversion of Control (IoC) is the mechanism to achieve loose-coupling between Objects dependencies. To achieve loose coupling and dynamic binding of the objects at runtime, the objects define their dependencies that are being injected by other assembler objects. Spring IoC container is the program that injects dependencies into an object and make it ready for our use.
Spring Framework IoC container classes are part of org.springframework.beans and org.springframework.context packages and provides us different ways to decouple the object dependencies.
Some of the useful ApplicationContext implementations that we use are;
· AnnotationConfigApplicationContext: For standalone java applications using annotations based configuration.
· ClassPathXmlApplicationContext: For standalone java applications using XML based configuration.
· FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
· AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.




 

111. What is a Spring Bean?

Ans:

Any normal java class that is initialized by 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.

112. What is the importance of Spring bean configuration file?

Ans:

We use Spring Bean configuration file to define all the beans that will be initialized by Spring Context. When we create the instance of Spring ApplicationContext, it reads the spring bean xml file and initialize all of them. Once the context is initialized, we can use it to get different bean instances.
Apart from Spring Bean configuration, this file also contains spring MVC interceptors, view resolvers and other elements to support annotations based configurations.

113. What are different ways to configure a class as Spring Bean?

Ans:

There are three different ways to configure Spring Bean.
XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring Bean.

Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:

@Configuration
@ComponentScan(value="com.journaldev.spring.main")
public class MyConfiguration {
@Bean
public MyService getService(){
return new MyService();
}
}

To get this bean from spring context, we need to use following code snippet:

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
MyConfiguration.class);
MyService service = ctx.getBean(MyService.class);

Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes.

114. What are different scopes of Spring Bean?

Ans:

There are five scopes defined for Spring Beans.
singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
prototype: A new instance will be created every time the bean is requested.
request: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
session: A new bean will be created for each HTTP session by the container.
global-session: This is used to create global session beans for Portlet applications.
Spring Framework is extendable and we can create our own scopes too, however most of the times we are good with the scopes provided by the framework.
To set spring bean scopes we can use “scope” attribute in bean element or @Scope annotation for annotation based configurations.

115. What is Spring Bean life cycle?

Ans:

Spring Beans are initialized by Spring Container and all the dependencies are also injected. When 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 by two ways – by implementing InitializingBean and DisposableBean interfaces or using init-method and destroy-method attribute in spring bean configurations.

116. How to get ServletContext and ServletConfig object in a Spring Bean?

Ans:

There are two ways to get Container specific objects in the spring bean.
1. Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for complete example of these aware interfaces, please read Spring Aware Interfaces
2. Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only though.
3. @Autowired
4. ServletContext servletContext;

117. What is Bean wiring and @Autowired annotation?

Ans:

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 spring framework also supports autowiring. 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.

118. What are different types of Spring Bean autowiring?

Ans:

There are four types of autowiring in Spring framework.
1. autowire byName
2. autowire byType
3. autowire by constructor
4. 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. For more details about these options, please read Spring Bean Autowiring.

119. Does Spring Bean provide thread safety?

Ans:

The default scope of Spring bean is singleton, so there will be only one instance per context. That means that all the having a class level variable that any thread can update will lead to inconsistent data. Hence in default mode spring beans are not thread-safe.
However we can change spring bean scope to request, prototype or session to achieve thread-safety at the cost of performance. It’s a design decision and based on the project requirements.

120. What is a Controller in Spring MVC?

Ans:

Just like MVC 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.


 

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

Ans:

@Component is used to indicate that a class is a component. These classes are used for auto detection and configured as 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 repository and a mechanism to store/retrieve/search data. 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.

122. What is DispatcherServlet and ContextLoaderListener?

Ans:

DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initialize all the beans that are configured. If annotations are enabled, it also scans the packages and configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.
ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. It’s 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.

123. What is ViewResolver in Spring?

Ans:

ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file.

InternalResourceViewResolver is one of the implementation of ViewResolver interface and we are providing the view pages directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will use view page located at /WEB-INF/views/home.jsp.

124. What is a MultipartResolver and when its used?

Ans:

MultipartResolver interface is used for uploading files – CommonsMultipartResolver and StandardServletMultipartResolver are two implementations provided by spring framework for file uploading. By default there are no multipart resolvers configured but to use them for uploading files, all we need to define a bean named “multipartResolver” with type as MultipartResolver in spring bean configurations.
Once configured, any multipart request will be resolved by the configured MultipartResolver and pass on a wrapped HttpServletRequest. Then it’s used in the controller class to get the file and process it.

125. How to handle exceptions in Spring MVC Framework?

Ans:

Spring MVC Framework provides following ways to help us achieving robust exception handling.
1. Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
2. 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.
3. HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create 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.

126. How to create ApplicationContext in a Java Program?

Ans:

There are following ways to create spring context in a standalone java program.
1. 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.
2. ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.
3. FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.

127. Can we have multiple Spring configuration files?

Ans:

For Spring MVC applications, we can define multiple spring context configuration files through contextConfigLocation. This location string can consist of multiple locations separated by any number of commas and spaces. For example;


appServlet
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation/WEB-INF/spring/appServlet/servlet-context.xml,/WEB-INF/spring/appServlet/servlet-jdbc.xml

We can also define multiple root level spring configurations and load it through context-param. For example;


contextConfigLocation/WEB-INF/spring/root-context.xml /WEB-INF/spring/root-security.xml

Another option is to use import element in the context configuration file to import other configurations, for example:

 

128. What is ContextLoaderListener?

Ans:

ContextLoaderListener is the listener class used to load root context and define spring bean configurations that will be visible to all other contexts. It’s configured in web.xml file.

129. How would you relate Spring MVC Framework to MVC architecture?

Ans:

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 delegate it to different controller handler methods.
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 HTMLs 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.

130. How to achieve localization in Spring MVC applications?

Ans:

Spring provides excellent support for localization or i18n through resource bundles. Basis steps needed to make our application localized are:
1. Creating message resource bundles for different locales, such as messages_en.properties, messages_fr.properties etc.
2. Defining messageSource bean in the spring bean configuration file of type ResourceBundleMessageSource or ReloadableResourceBundleMessageSource.
3. For change of locale support, define localeResolver bean of type CookieLocaleResolver and configure LocaleChangeInterceptor interceptor. 4. Use spring:message element in the view pages with key names, DispatcherServlet picks the corresponding value and renders the page in corresponding locale and return as response.



 

131. How can we use Spring to create Restful Web Service returning JSON response?

Ans:

We can use Spring Framework to create Restful web services that returns JSON data. Spring provides integration with Jackson JSON API that we can use to send JSON response in restful web service.
We would need to do following steps to configure our Spring MVC application to send JSON response:
1. Adding Jackson JSON dependencies, if you are using Maven it can be done with following code:

2. <!-- Jackson -->
3. <dependency>
4. <groupId>com.fasterxml.jackson.core</groupId>
5. <artifactId>jackson-databind</artifactId>
6. <version>${jackson.databind-version}</version>
7. </dependency>
8. Configure RequestMappingHandlerAdapter bean in the spring bean configuration file and set the messageConverters property to MappingJackson2HttpMessageConverter bean. Sample configuration will be:
9. <!-- Configure to plugin JSON as request and response in method handler -->
10. <beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
11. <beans:property name="messageConverters">
12. <beans:list>
13. <beans:ref bean="jsonMessageConverter"/>
14. </beans:list>
15. </beans:property>
16. </beans:bean>
17. <!-- Configure bean to convert JSON to POJO and vice versa -->
18. <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
19. </beans:bean>
20. In the controller handler methods, return the Object as response using @ResponseBodyannotation. Sample code:
21. @RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET)
22. public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) {
23. logger.info("Start getEmployee. ID="+empId);
24.
25. return empData.get(empId);
26. }

27. You can invoke the rest service through any API, but if you want to use Spring then we can easily do it using RestTemplate class.

132. What are the advantages of Spring MVC over Struts MVC ?

Ans:

Following are some of the advantages of Spring MVC over Struts MVC –
Spring’s MVC is very versatile and flexible based on interfaces but Struts forces Actions and Form object into concrete inheritance.
Spring provides both interceptors and controllers, thus helps to factor out common behavior to the handling of many requests.
Spring can be configured with different view technologies like Freemarker, JSP, Tiles, Velocity, XLST etc. and also you can create your own custom view mechanism by implementing Spring View interface.
In Spring MVC Controllers can be configured using DI (IOC) that makes its testing and integration easy.
Web tier of Spring MVC is easy to test than Struts web tier, because of the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.
Struts force your Controllers to extend a Struts class but Spring doesn’t, there are many convenience Controller implementations that you can choose to extend.
In Struts, Actions are coupled to the view by defining ActionForwards within a ActionMapping or globally. SpringMVC has HandlerMapping interface to support this functionality.
With Struts, validation is usually performed (implemented) in the validate method of an ActionForm. In SpringMVC, validators are business objects that are NOT dependent on the Servlet API which makes these validators to be reused in your business logic before persisting a domain object to a database.

133. What are some of the important Spring annotations you have used?

Ans:

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 response, usually for sending XML or JSON data as 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 scope of the spring bean.
· @Configuration, @ComponentScan and @Bean – for java based configurations.
· AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around, @Pointcut etc.

134. Can we send an Object as the response of Controller handler method?

Ans:

Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.

135. How to upload file in Spring MVC Application?

Ans:

Spring provides built-in support for uploading files through MultipartResolver interface implementations. It’s very easy to use and requires only configuration changes to get it working. Obviously we would need to write controller handler method to handle the incoming file and process it.

136. How to validate form data in Spring Web MVC Framework?

Ans:

Spring supports JSR-303 annotation based validations as well as provide Validator interface that we can implement to create our own custom validator. For using JSR-303 based validation, we need to annotate bean variables with the required validations.
For custom validator implementation, we need to configure it in the controller class.

137. What is Spring MVC Interceptor and how to use it?

Ans:

Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client request at three places – preHandle, postHandle and afterCompletion.
We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.
We need to configure interceptors in the spring bean configuration file. We can define an interceptor to intercept all the client requests or we can configure it for specific URI mapping too.

138. What is Spring JdbcTemplate class and how to use it?

Ans:

Spring Framework provides excellent integration with JDBC API and provides JdbcTemplate utility class that we can use to avoid bolier-plate code from our database operations logic such as Opening/Closing Connection, ResultSet, PreparedStatement etc.

139. How to use Tomcat JNDI DataSource in Spring Web Application?

Ans:

For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration file and then inject it to spring beans as dependencies. Then we can use it with JdbcTemplate to perform database operations.

140. How would you achieve Transaction Management in Spring?

Ans:

Spring framework provides transaction management support through Declarative Transaction Management as well as programmatic transaction management. Declarative transaction management is most widely used because it’s easy to use and works in most of the cases.
We use annotate a method with @Transactional annotation for Declarative transaction management. We need to configure transaction manager for the DataSource in the spring bean configuration file.




 

141. What is Spring DAO?

Ans:

Spring DAO support is provided to work with data access technologies like JDBC, Hibernate in a consistent and easy way. For example we have JdbcDaoSupport, HibernateDaoSupport, JdoDaoSupport and JpaDaoSupport for respective technologies.
Spring DAO also provides consistency in exception hierarchy and we don’t need to catch specific exceptions.

142. How to integrate Spring and Hibernate Frameworks?

Ans:

We can use Spring ORM module to integrate Spring and Hibernate frameworks, if you are using Hibernate 3+ where SessionFactory provides current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with dependency injection for the integration.
Also Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for hibernate boiler-plate code for transaction management.
For better understanding you should go through following tutorials:
· Spring Hibernate Integration Example
· Spring MVC Hibernate Integration Example

143. What is Spring Security?

Ans:

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 following posts to learn how to use Spring Security framework.
· Spring Security in Servlet Web Application
· Spring MVC and Spring Security Integration Example

144. How to inject a java.util.Properties into a Spring Bean?

Ans:

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;

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

If you are using annotation to configure the spring bean, then you can inject property like below.

@Value("${maxReadResults}")
private int maxReadResults;

145. Name some of the design patterns used in Spring Framework?

Ans:

Spring Framework is using a lot of design patterns, some of the common ones are:
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

146. What are some of the best practices for Spring Framework?

Ans:

Some of the best practices for Spring Framework are:
1. Avoid version numbers in schema reference, to make sure we have the latest configs.
2. Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
3. For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with listener.
4. Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
5. For application level properties, best approach is to create a property file and read it in the spring bean configuration file.
6. For smaller applications, annotations are useful but for larger applications annotations can become a pain. If we have all the configuration in xml files, maintaining it will be easier.
7. Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO beans use @Repository.
8. Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that gets usually added when you create projects through Spring Tool Suite templates.
9. If you are using Aspects, make sure to keep the join pint as narrow as possible to avoid advice on unwanted methods. Consider custom annotations that are easier to use and avoid any issues.
10. Use dependency injection when there is actual benefit, just for the sake of loose-coupling don’t use it because it’s harder to maintain.
That’s all for Spring Framework interview questions. I hope these questions will help you in coming Java EE interview. I will keep on adding more questions to the list as soon as I found them. If you know some more questions that should be part of the list, make sure to add a comment for it and I will include it.

147. What is Spring?

Ans:

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.

148. What are features of Spring?

Ans:

Lightweight:
Spring is lightweight when it comes to size and transparency. The basic version of 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 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 less environments.

149. Describe the Spring Framework?

Ans:

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.

150. What is Spring Java Based Configuration?

Ans:

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.


 

151. Describe some of the standard Spring events?

Ans:

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.

152. Which are the Spring framework modules?

Ans:

The basic modules of the Spring framework are :
Core module
Bean module
Context module
Expression Language module
JDBC module
ORM module
OXM module
Java Messaging Service(JMS) module
Transaction module
Web module
Web-Servlet module
Web-Struts module
Web-Portlet module

153. What are the types of Dependency Injection Spring supports?

Ans:

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.

154. What is Spring IOC container?

Ans:

The Spring IOC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The spring container uses dependency injection (DI) to manage the components that make up an application.

155. What are Spring beans?

Ans:

The objects that form the backbone of the users 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.

156. What bean scopes does Spring support? Explain them.

Ans:

The Spring Framework supports following five scopes, three of which are available only if the users use a web-aware Application Context.
Singleton: This scopes the bean definition to a single instance per Spring IoC container.
Prototype: This scopes a single bean definition to have any number of object instances.
Request: This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext
Session: This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
Global-session: This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

157. Explain Bean lifecycle in Spring framework?

Ans:

Following is sequence of a bean lifecycle in Spring:
Instantiate: First the spring container finds the bean’s definition from the XML file and instantiates the bean.
Populate properties: Using the dependency injection, spring populates all of the properties as specified in the bean definition.
Set Bean Name: If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
Set Bean factory: If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
Pre Initialization: Also called post process of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
Initialize beans: If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
Post Initialization: – If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
Ready to use: Now the bean is ready to use by the application
Destroy: If the bean implements DisposableBean , it will call the destroy() method

158. What is Spring?

Ans:

Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

159. What are benefits of using spring?

Ans:

Following is the list of few of the great benefits of using Spring Framework:
Lightweight – Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
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’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over engineered or less popular web frameworks.
Transaction Management – Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
Exception Handling – Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.

160. What are the different modules in Spring framework?

Ans:

Following are the modules of the Spring framework:
Core module
Bean module
Context module
Expression Language module
JDBC module
ORM module
OXM module
Java Messaging Service(JMS) module
Transaction module
Web module
Web-Servlet module
Web-Struts module
Web-Portlet module



 

161. What is Spring configuration file?

Ans:

Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.

162. What is Dependency Injection?

Ans:

Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways and Dependency Injection is merely one concrete example of Inversion of Control.
This concept says that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (the IOC container) is then responsible for hooking it all up.

163. What are the different types of IoC (dependency injection)?

Ans:

Types of IoC are –
Constructor-based dependency injection – Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
Setter-based dependency injection – Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

164. Which DI would you suggest Constructor-based or setter-based DI?

Ans:

Since you can mix both, Constructor- and Setter-based DI, it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Note that the use of a @Required annotation on a setter can be used to make setters required dependencies.

165. What are the benefits of IOC?

Ans:

The main benefits of IOC or dependency injection are –
It minimizes the amount of code in your application.
It makes your application easy to test as it doesn’t require any singletons or JNDI lookup mechanisms in your unit test cases.
Loose coupling is promoted with minimal effort and least intrusive mechanism.
IOC containers support eager instantiation and lazy loading of services.

166. What is AOP?

Ans:

Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules.

167. What is Spring IoC container?

Ans:

The Spring IoC creates the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application.

168. What are types of IoC containers? Explain them.

Ans:

There are two types of IoC containers –
Bean Factory container – This is the simplest container providing basic support for DI .The BeanFactory is usually preferred where the resources are limited like mobile devices or applet based applications
Spring ApplicationContext Container – This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.
Give an example of BeanFactory implementation.
The most commonly used BeanFactory implementation is the XmlBeanFactory class. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application.

169. What are the common implementations of the ApplicationContext?

Ans:

The three commonly used implementation of ‘Application Context’ are –
FileSystemXmlApplicationContext – This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor.
ClassPathXmlApplicationContext – This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.
WebXmlApplicationContext – This container loads the XML file with definitions of all beans from within a web application.

170. What is the difference between Bean Factory and ApplicationContext?

Ans:

Following are some of the differences –
Application contexts provide a means for resolving text messages, including support for i18n of those messages.
Application contexts provide a generic way to load file resources, such as images.
Application contexts can publish events to beans that are registered as listeners.
Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context.
The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.




 

171. What are Spring beans?

Ans:

The objects that form the backbone of your 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 you supply to the container, for example, in the form of XML definitions.

172. What does a bean definition contain?

Ans:

The bean definition contains the information called configuration metadata which is needed for the container to know the followings –
How to create a bean
Bean’s lifecycle details
Bean’s dependencies

173. How do you provide configuration metadata to the Spring Container?

Ans:

There are following three important methods to provide configuration metadata to the Spring Container –
XML based configuration file.
Annotation-based configuration
Java-based configuration

174. How do add a bean in spring application?

Ans:

Check the following example –


xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

175. How do you define a bean scope?

Ans:

When defining a < bean> in Spring, you have the option of declaring a scope for that bean. For example, to force Spring to produce a new bean instance each time one is needed, you should declare the bean’s scope attribute to be prototype. Similar way if you want Spring to return the same bean instance each time one is needed, you should declare the bean’s scope attribute to besingleton.

176. What bean scopes does Spring support? Explain them.

Ans:

The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext.
singleton – This scopes the bean definition to a single instance per Spring IoC container.
prototype – This scopes a single bean definition to have any number of object instances.
request – This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
session – This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-session – This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

177. What is default scope of bean in Spring framework?

Ans:

The default scope of bean is Singleton for Spring framework.
Are Singleton beans thread safe in Spring Framework?
No, singleton beans are not thread-safe in Spring framework.

178. Explain Bean lifecycle in Spring framework?

Ans:

Following is sequence of a bean lifecycle in Spring –
Instantiate – First the spring container finds the bean’s definition from the XML file and instantiates the bean..
Populate properties – Using the dependency injection, spring populates all of the properties as specified in the bean definition.
Set Bean Name – If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.
Set Bean factory – If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.
Pre Initialization – Also called postprocess of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.
Initialize beans – If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
Post Initialization – If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
Ready to use – Now the bean is ready to use by the application.
Destroy – If the bean implements DisposableBean , it will call the destroy() method .

179. What is a DispatcherServlet?

Ans:

The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses.

180. What are the types of advice?

Ans:

Spring aspects can work with five kinds of advice mentioned below –
before – Run advice before the a method execution.
after – Run advice after the a method execution regardless of its outcome.
after-returning – Run advice after the a method execution only if method completes successfully.
after-throwing – Run advice after the a method execution only if method exits by throwing an exception.
around – Run advice before and after the advised method is invoked.


 

181. What is XML Schema based aspect implementation?

Ans:

Aspects are implemented using regular classes along with XML based configuration.

182. What is @AspectJ? based aspect implementation?

Ans:

@AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.

183. How JDBC can be used more efficiently in spring framework?

Ans:

JDBC can be used more efficiently with the help of a template class provided by spring framework called as JdbcTemplate.

184. How JdbcTemplate can be used?

Ans:

With use of Spring JDBC framework the burden of resource management and error handling is reduced a lot. So it leaves developers to write the statements and queries to get the data to and from the database. JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.

185. What are the types of the transaction management Spring supports?

Ans:

Spring supports two types of transaction management –
Programmatic transaction management – This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
Declarative transaction management – This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.

186. Which of the above transaction management type is preferable?

Ans:

Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.

187. What is Spring MVC framework?

Ans:

The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.