Spring Overview Interview Questions Part III

How Spring relate to MVC framework ?

In Spring's Web MVC framework : a DispatcherServlet that dispatches requests to handlers.The default handler is a very simple Controller interface, just offering a ModelAndView handleRequest(request,response) method.

Learn more about Spring in our Video Tutorial

How to setup MessageSources in Spring?

Spring currently provides two MessageSource implementations. These are the ResourceBundleMessageSource and the StaticMessageSource.

What is ApplicationContext in details?

The basis for the context package is the ApplicationContext interface, located in the org.springframework.context package. Deriving from the BeanFactory interface, it provides all the functionality of BeanFactory.

To allow working in a more framework-oriented fashion, using layering and hierarchical contexts, the context package also provides the following functionality :

  1. MessageSource, providing access to messages in i18n-style.

  2. Access to resources, such as URLs and files.

  3. Event propagation to beans implementing the ApplicationListener interface.

  4. Loading of multiple (hierarchical) contexts, allowing each to be focused on one particular layer, for example the web layer of an application.

As the ApplicationContext includes all functionality of the BeanFactory, it is generally recommended that it be used over the BeanFactory, except for a few limited situations such as perhaps in an Applet, where memory consumption might be critical, and a few extra kilobytes might make a difference.

Explain Bean Lifecycle in Spring ?

The Spring Framework provides InitializingBean and DisposableBean marker interface. Implementing these interfaces will result in the container calling afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction.

  1. Initialization callbacks

    There are two ways you can achive the initialization work after all necessary properties on the bean are set by the container.

    1. Use 'init-method' in XML configuration

      You can do initialization work in init() method.

    2. Implementing the org.springframework.beans.factory.InitializingBean interface

      You can do initialization work in afterPropertiesSet() method.

      void afterPropertiesSet() throws Exception;

  2. Destruction callbacks

    Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed.

    There are two ways you can achive the destroy.

    1. use 'destroy-method' in XML configuration

      You can do cleanup work in cleanup() method.

    2. Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a callback when the container containing it is destroyed.

What do you mean by Advice? and what are the Advices?

Action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join point.

Types of advice :

  • Before advice :
    Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).

  • After returning advice :
    Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception.

  • After throwing advice :
    Advice to be executed if a method exits by throwing an exception.

  • After (finally) advice :
    Advice to be executed regardless of the means by which a join point exits (normal or exceptional return).

  • Around advice : Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception

What do you mean by JointPoint?

A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution.

What is AOP - Aspect-oriented programming ?

Spring AOP enables Aspect-Oriented Programming in spring applications. In AOP, aspects enable the modularization of concerns such as transaction management, logging or security that cut across multiple types and objects (often termed crosscutting concerns).

AOP makes it possible to modularize and separate these services and then apply them declaratively to the components and we can focus on our own specific concerns.

Transaction parameters are like EJB,
PROPAGATION_REQUIRED
PROPAGATION_REQUIRED_NEW etc

What is RowCallbackHandler?
  • The RowCallbackHandler interface extracts values from each row of a ResultSet.

  • It has one method- processRow(ResultSet) which is called for each row in ResultSet.

What is PreparedStatementCreator?
  • PreparedStatementCreator is one of the most common used interfaces for writing data to database.

  • It has one method- createPreparedStatement(Connection) which is responsible for creating a PreparedStatement. Does not need to handle SQLExceptions.

What are Bean scopes in Spring Framework?

If you are using ApplicationContext then there are five scopes (singleton, prototype, request, session, globalsession) and if you are using BeanFactory then two scopes (singleton, prototype).

  • singleton :
    Scopes a single bean definition to a single object instance per Spring IoC container. Only one singleton object will be created. Default scope.

  • prototype :
    Scopes a single bean definition to any number of object instances. Every call create new object like Emp emp = new Emp();

  • request :
    Scopes a 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 ApplicationContext.

  • session :
    Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

  • global session :
    Scopes a 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 ApplicationContext.

Lifecycle interfaces in Spring ?
  • InitializingBean

  • DisposableBean

InitializingBean :

OR


DisposableBean :

OR

What are the common implementations of the ApplicationContext?
  • ClassPathXmlApplicationContext :
    It Loads context definition from an XML file located in the classpath.
    ApplicationContext context = new ClassPathXmlApplicationContext("bean_test.xml");

  • FileSystemXmlApplicationContext :
    It loads context definition from an XML file in the filesystem.
    ApplicationContext context = new FileSystemXmlApplicationContext("bean_test.xml");

  • XmlWebApplicationContext :
    It loads context definition from an XML file contained within a web application.

What is the difference between BeanFactory and ApplicationContext ?
  • The ApplicationContext builds on top of the BeanFactory (it's a subclass) and adds other functionality such as easier integration with Springs AOP features, message resource handling (for use in internationalization), event propagation, declarative mechanisms to create the ApplicationContext and optional parent contexts, and application-layer specific contexts such as the WebApplicationContext, among other enhancements.

  • Application Context is suitable for J2EE Applications.

  • The main usage scenario when you might prefer to use the BeanFactory is when memory usage is the greatest concern (such as in an applet where every last kilobyte counts), and you don't need all the features of the ApplicationContext.

What is ApplicationContext in Spring?
  • The ApplicationContext builds on top of the BeanFactory (it's a subclass) and adds other functionality such as easier integration with Springs AOP features, message resource handling (for use in internationalization), event propagation, declarative mechanisms to create the ApplicationContext and optional parent contexts, and application-layer specific contexts such as the WebApplicationContext, among other enhancements.

  • The BeanFactory provides the configuration framework and basic functionality, while the ApplicationContext adds enhanced capabilities to it, some of them perhaps more J2EE and enterprise-centric. In general, an ApplicationContext is a complete superset of a BeanFactory, and any description of BeanFactory capabilities and behavior should be considered to apply to ApplicationContexts as well.

  • In a J2EE-environment, the best option is to use the ApplicationContext, since it offers all the features of the BeanFactory and adds on to it in terms of features, while also allowing a more declarative approach to use of some functionality, which is generally desirable.

What is BeanFactory and how can configure BeanFactory?

The BeanFactory is the actual container which instantiates, configures, and manages a number of beans. These beans typically collaborate with one another, and thus have dependencies between themselves. These dependencies are reflected in the configuration data used by the BeanFactory.

Three ways you can configure BeanFactory.

  1. OR

  2. OR

What is Spring ? and What are the Benefits/Advantages of Using Spring Framework?

Spring is an open source framework created to address the complexity of enterprise application development.

  • Lightweight container.

  • No App Server Dependent like EJB & JNDI Calls.

  • Objects are created Lazily , Singleton - configuration.

  • Components can added Declaratively. Initialization of properties is easy. No need to read from properties file.

  • Declarative transaction, security and logging service - AOP application code is much easier to unit test.

  • With a Dependency Injection approach, dependencies are explicit, and evident in constructor or JavaBean properties.

  • Spring's configuration management services can be used in any architectural layer, in whatever runtime environment.

  • Spring can effectively organize your middle tier objects.

  • Not requires special deployment steps.

Learn about Spring from our Experts

What is Dependency Injection ?

The basic concept of the Inversion of Control pattern (also known as dependency injection) is 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.