Find the Interview questions and answers about most popular Spring framework. Spring is a most popular application development framework for Java.
1.What is Spring and why we need to use Spring?
Spring is an open source lightweight framework it aims to make J2EE development easier and solves the problems in traditional J2EE approach. Spring handles the infrastructure so you can focus on your application. Spring uses Plain old Java Objects (POJO’s) which keep your code concise, simple and modular. Spring is designed from the ground up to help you write code that’s easy to do unit and integration testing.
2.Design Patterns Used in the Spring Framework?
- Singleton Design Pattern – Beans defined in spring config files are singletons by default.
- Proxy Design Pattern - It is heavily used in Spring AOP, and remoting.
- Template method Design Pattern -It is used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc.). For example JdbcTemplate, JmsTemplate, JpaTemplate.
- Model View Controller
- Front Controller
- View Helper.
3. Different modules in Spring Framework?
- The Core container module
- Application context module
- AOP module (Aspect Oriented Programming)
- JDBC abstraction and DAO module
- O/R mapping integration module (Object/Relational)
- Web module
- MVC framework module.
4. Difference between BeanFactory and ApplicationContext?
A BeanFactory is the simplest form of container, it pretty much just instantiates and configures beans.But when more advanced framework services are needed, Spring’s ApplicationContext is the container to use.Using Application context you can achieve Automatic BeanPostProcessor registration, Automatic BeanFactoryPostProcessor registration,Convenient MessageSource access (for i18n) and ApplicationEvent publication.
5.What are the different types of spring beans scopes?
Spring has five different types of bean scopes.
- Singleton – Scopes a single bean definition to a single object instance per Spring IoC container. It means that every time a request for this bean is made, same instance is returned.
- Prototype – Scopes a single bean definition to any number of object instances. it means that every time a request for this bean is made, a new instance is created.
- Request – Single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring Application Context.
- Session - single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring Application Context.
- Global session - Single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring Application Context.
6.What is the Difference between Singleton and Prototype Beans?
Please find the answer in the previous question.
7.Explain About Bean Lift Cycle?
1.First Spring container find the bean definition from context file and instantiates the bean.
2. Spring injects values and bean references into the bean’s properties.
3. If the bean implements BeanNameAware, Spring passes the bean’s ID to the set-
4. If the bean implements BeanFactoryAware, Spring calls the setBeanFactory() method, passing in the bean factory itself.
5. If the bean implements ApplicationContextAware, Spring will call the set ApplicationContext() method, passing in a reference to the enclosing application context.
6. If any of the beans implement the BeanPostProcessor interface, Spring calls their postProcessBeforeInitialization() method.
7 . If any beans implement the InitializingBean interface, Spring calls their afterPropertiesSet() method. Similarly, if the bean was declared with an init-method, then the specified initialization method will be called.
8. If there are any beans that implement BeanPostProcessor, Spring will call their postProcessAfterInitialization() method.
9. At this point, the bean is ready to be used by the application and will remain in the application context until the application context is destroyed.
10. If any beans implement the DisposableBean interface, then Spring will call their destroy() methods. Likewise, if any bean was declared with a destroy method, then the specified method will be called.
8.What is mean by Dependency Injection?
Writing the Java Classes which should be independent as independent as possible of other Java classes then only we can achieve loose coupling because loose coupling promotes greater reusability, easier maintainability.
Dependency Injection (IOC) is a technique or design pattern to achieve this loose coupling. You don’t need to create object or directly connect your components and services together in code you can describe which services are needed by which components in a configuration file then IOC container will take care of Object creation and dependency collaboration.
9.Different types of Dependency Injection?
Three Types of Dependency Injection are
1. Constructor Injection.
2. Setting Injection
3. Interface Injection.
10.What is Bean wiring and Different types?
Wiring is typically performed within a Spring container using an XML file. This XML file contains configuration information for all of the components of an application, along with information that helps the container perform DI to associate beans with other beans that they depend on.
byName—Attempts to match all properties of the autowired bean with beans
that have the same name (or ID) as the properties. Properties for which there’s
no matching bean will remain unwired.
byType— Attempts to match all properties of the autowired bean with beans
whose types are assignable to the properties. Properties for which there’s no
matching bean will remain unwired.
constructor— Tries to match up a constructor of the autowired bean with
beans whose types are assignable to the constructor arguments.
autodetect—Attempts to apply constructor autowiring first. If that fails,
byType will be tried.
11.Different Types of Spring Transaction Management ?
Transaction management is required to ensure the data integrity and consistency in database.Spring has two types Transaction management.
1.Declarative :Transaction is applied,instead of implementing in your business logic place that means with the help simple configuration you apply a common functionality across all your code.
2.Programmatic : When you add code some functionality by yourself so that you could control each and everything by yourself. This usually mixes the unrelated functionality in your business logic.
12.Difference between JDBC module in spring and using hibernate?
Hibernate is a really huge solution with data persistence and ORM including JPA implementation. Also there are defined many ways how to manage entities in Hibernate, how to persist, transactions, etc. In hibernate you can use SQL, HQL or java annotations.
JDBC template is just a simple tool that helps you to manage SQL queries and transactions. Probably it is better JDBC wrapper or helper. Also if you prefer managing database queries (SQL) yourself or if you are a beginner, try Spring JdbcTemplate to understand, how it works. Even if you are working on a bigger application, think about using Hibernate.
13.How to Configure Hibernate in Spring?
</pre> <bean id="hibernateDao" class="HibernateAccessDao"> <property name="hibernateTemplate"> <ref bean="hibernateTemplate"/> </property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:330/dbname"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mappingResources"> <list> <value>Users.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value>hibernate.dialect=org.hibernate.dialect.HSQLDialect</value> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref bean="mySessionFactory"/> </property> </bean> </beans> <pre>
1.The bean “datasource” is used to configure the properties of the DB.
2.The bean “mySessionFactory” is used to maintain the session of hibernate. This is taken care by the spring container now.
3.The property “mappingResources” takes the list of hbm files which will be mappd to this session. Also the datasource property is set in this bean.
4.The bean hibernateTemplate is the one used to interact with the DB.
14.What is Spring HibernateTemplate?
It is helper Class used to automatically open and close sessions and commit or rollback transactions after your code executed.Here you are coupling your application tightly to the spring framework. For this reason, Spring recommends that HibernateTemplate no longer be used.
15.What is Spring AOP? What is PointCut?
The main strength Spring Framework is its robust and flexible aspect oriented programming infrastructure.Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects.
Pointcut: A pointcut defines what advices are required at what join points.
transaction management that cut across multiple types and objects.
16.How do you control Concurrent active sessions using Spring Security?
In your security-application context you need to configure like this.you can limit the number of user session using following code.
<session-management invalid-session-url="/logout.html"> <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" /> </session-management>
17.Different Types of Advice in Spring AOP?
1. Before advice – It will Run before the method execution.
2. After returning advice – It will Run after the method returns a result.
3. After throwing advice – It will Run after the method throws an exception.
4.Around advice – It will Run around the method execution and it combines all three advice’s above.
18.What is Around Advice?
Basic before and after advice have some limitations.Around Advice is combination of both Before and After Advice. Specifically, it’s tricky to share information between before advice and after advice without resorting to storing that information in member variables.Around advice has an advantage over before and after advice in this regard. With around advice, you can accomplish the same thing as you can with distinct before and after advice, but do it in a single method. Since the entire set of advice takes place in a single method, there’s no need to retain state in a member variable.
19.What is Spring Batch?
Spring Batch is part of Spring.It is a lightweight, comprehensive open source framework for batch processing – execution of a series of jobs.Spring Batch provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management.
20.Difference between context annotation config and context component scan?
It is used to activate annotations in beans already registered in the application context.
<context:component-scan> : It has same functionality like annotation config but also scans packages to find and register beans within the application context.
21.Explain Spring MVC Lifecycle?
1. The client sends a request to web container in the form of http request.This incoming request is intercepted by Front controller called DispatcherServlet.
2. DispatcherServlet tries to find out appropriate Handler Mappings.
3. With the help of Handler Mappings, the DispatcherServlet will dispatch the request to appropriate Controller.
4. The Controller tries to process the request and returns the Model and View object in form of ModelAndView instance to the Front Controller.
5. DispatcherServlet then tries to resolve the View (which can be JSP or Freemarker or Velocity etc) by with help of the View Resolver object.
6. Finally the selected view is then rendered back to client.
22.How to Integrate Spring Security in Spring MVC Applications?
Please refer the following posts for answer.
23.How to Integrate Spring in JSF2?
Find the Answer in my post about Spring Integration in JSF .
Don’t miss Hibernate Interview Questions and Answers.
Also read a article about Best Books for Spring and Hibernate Frameworks
I hope you enjoyed this Spring Interview Questions and Answers Post.If you know some more questions please share the same using below comment section.