Tuesday, March 18, 2008

Spring Framework Interview QA

What is Spring Framework?

Now the answer of this question can go to a great depth.But my focus here is to cover following points under the periphery of answer of question framed:

-Definition of Spring
-Structure/Modules/Components of Spring

Definition: Spring is a lightweight container,sometimes referred as framework also, which provides runtime support for different enterprise level services and frameworks.Spring has Inversion of Control(IoC) and Aspect Oriented Programming(AOP) concepts at its core(These concepts will be answered under separate questions).Spring has provided a platform for existing projects,technologies,concepts to combine and provide a cohesive enterprise level application development support.

Spring framework is consisted of seven modules as shown in the diagram below:

Spring Framework(Image Source: springframework.org)



Spring Framework(Image Source: springframework.org)
Core package
-most fundamental
-provides the IoC and Dependency Injection features
-The concept of BeanFactory that helps in decoupling configuration and specification of dependencies from your actual program logic.

Context package
- build on top of Core package
- provides a way to access objects similar to JNDI way.
-support for internationalization (I18N),event-propagation, resource-loading, and transparent creation of contexts.

DAO package
-provides a JDBC-abstraction layer
-programmatic as well as declarative transaction management
-POJOs (plain old Java objects) support.

ORM package
-provides integration layers for O/R mapping APIs, including JPA, JDO, Hibernate, and iBatis.

AOP package
- provides an aspect-oriented programming implementation
- defining method-interceptors and pointcuts to cleanly decouple code implementing functionality

Web package
-provides basic web-oriented integration features, such as multipart file-upload functionality, the initialization of the IoC container using servlet listeners and a web-oriented application context.
- integrate this package when using Spring with WebWork or Struts

MVC package
-provides clean separation between domain model code and web forms

Why is Spring Framework needed anyway?

The main aim of Spring is to make J2EE easier to use and promote good programming practice.It does not reinvent the wheel but makes existing technologies easier to use. The main advantages of Spring framework are enumerated as given below:-

-No matter whether you use EJBs or Struts Framework or any other framework for writing business objects, Spring organizes your business objects in an effective manner with configuration management services on any runtime environment.You can keep one calling mechanism for your business objects while changing the implementation technology of them altogether.
-Spring allows you to get rid of EJBs,if one wants to,no more compulsory to have,with alternative technologies like POJOs for building business objects and AOP provides a way to handle declarative transaction management, making EJB container absolutely not required.
-Increased development productivity
-Increased runtime performance
-Improving test coverage as unit testing of code can easily be done.
-Improving application quality
-Easier manageability of code in Integration technology.
-A consistent data access mechanism either using JDBC or O/R mapping techniques.
-Spring is portable between application servers which avoids anything platform-specific or non-standard in the developer's view, and most of the application servers.

What do you understand by Inversion of Control/Dependency Injection?

Spring is an Inversion of Control container through its bean factory concept.IoC helps in loose coupling of the code .Spring is most closely identified with a flavor of Inversion of Control known as Dependency Injection(DI)--a name coined by Martin Fowler, Rod Johnson and the PicoContainer team in late 2003.DI is an old concept which caught the fancy of Java EE community not so long ago.DI is quite useful in test driven development and avoiding dependencies on other collaborating objects helps in building unit tests of objects behavior that is under test.

It follows famous Hollywood principle "Don't call me.I will call you". IoC moves the responsibility for making things happen into the framework, and away from application code. Whereas your code calls a traditional class library, an IoC framework calls your code. It segregates the calling mechanism of methods from actual implementation.

Dependency Injection is a form of IoC.In DI an object uses the other object to provide a specific functionality.It removes explicit dependence on container APIs.The ordinary Java methods are used for injecting dependencies by collaborating objects or configuration values into application object instances. With Dependency Injection the container figures out that a component needs an X object, and provides it to it at runtime. The container does this figuring out based on method signatures (usually JavaBean properties or constructors) and, possibly, configuration data such as XML.

DI can be accomplished either by Setter Injection or Constructor Injection and Spring supports both.

Some advantages of DI:

-No need for look up code at runtime, hence simpler to write and maintain. JavaBean setter method or constructors arguments are used to introduce DI in Spring.

-Easier testing of JavaBeans through JUnits.

-Spring framework provides strongly typed dependencies which a developer needs not be bothered about and type mismatches are raised as errors when the framework configures the application.

-With a DI approach, dependencies are explicit, and evident in constructor or JavaBean properties.

-Spring is non invasive that means using it won't invade your code with dependency on its APIs.No dependency on container APIs of most business objects. Any third party code or any POJO can be introduced as a Spring Bean.

-Spring BeanFactories are very lightweight,can be used inside applets, as well as standalone Swing applications,work fine withing EJB containers as well.

What is BeanFactory?


In core packages of Spring org.springframework.beans.factory there is an interface named BeanFactory that can be implemented in various ways.It represents a generic factory that enables objects to be retrieved by name and which can manage relationships between objects.A BeanFactory contains different beans definitions which can be instantiated whenever a client wishes to do so , it is, hence, associated with life cycle of bean instances.

Bean factories support two modes of object:
-
Singleton : a single,uniquely named, shared instance of an object which will be retrieved on lookup. It is the default, and most often used. It's ideal for stateless service objects.
-
Prototype or non-singleton: each retrieval results in an independent object creation.It could be used in stateful service objects scenarios where each caller has its own independent object.

The most commonly used bean factory objects are:

-XmlBeanFactory which parses a simple XML structure defining classes and properties of named objects.The DTD is provided to make authoring easier.
-
DefaultListableBeanFactory
parses bean definitions in properties files, and create BeanFactories programmatically.

Explain ApplicationContext in Spring framework.


A Spring ApplicationContext is a subinterface of BeanFactory.It is somewhat similar to BeanFactory in terms that both define beans,bind them together and make them available on request.In its functioning and ApplicationContext has following advanced features:

-Resolving Messages, supporting internationalization
-Support for an eventing mechanism, allowing application objects to publish events and they can register to be notified of events optionally.
-Supports generic loading and access of file resources like image files.
-Supports customization of container behavior through automatic recognition of special application-specific or generic, bean definitions.

What is Aspect Oriented Programming and how is it related with Spring?

Aspect Oriented Programming(AOP) is a paradigm of developmental approach which is based on:

-separation of concerns encompasses breaking down a program in parts which overlap in functionality as little as possible.
-cross-cutting concerns is how modules,classes,procedures intersect each other and defy concern like encapsulation
-advancement in modularization.

An AOP language consists of crosscutting expressions that encapsulate the concern in one place. AspectJ has a number of such expressions and encapsulates them in a special class, an aspect.

An aspect can

-change the behavior of the base code (the non-aspect part of a program) by applying advice(additional behavior) at various joint points (points in a program) specified by query called a point cut (that detects whether a given join point matches).

-make structural changes to other classes, like adding members or parents.

Spring implements AOP using

-dynamic proxies (where an interface exists)
or
-CGLIB byte code generation at runtime (which enables proxying of classes). It works well in any application server and standalone environment so there is no vebdor dependency.

-Spring can use AOP for declarative transaction management eliminating the need of EJB conatiner or JTA for achieving the same.
-Spring AOP supports method interception and both stateful (one instance per advised object) and stateless interceptors (one instance for all advice).
-Spring AOP can be used to implement application-specific aspects also.It all depends upon how much comfortable you are with Aspect concepts rather Spring AOP capabilities.
-Spring AOP integrates transparently with the Spring BeanFactory concept.

What are the problems you have with JDBC and how does Spring framework help to resolve them?


JDBC helps in accessing underlying RDBMS but it sometimes be quite cumbersome to use them and in following situations it become problematic:
-You have to ensure that ResultSets, Statements and (most importantly) Connections are closed after use. Hence correct use of JDBC results in a lot of code which is a common source of errors. Connection leaks can quickly bring applications down under load.
-The SQLException does not provide much information about what actually the probelm is as JDBC does not offer an exception hierarchy, but throws SQLException in response to all errors.The meaning of these values varies among databases.

Spring addresses these problems in two ways:

-By providing APIs that move tedious and error-prone exception handling out of application code into the framework. The framework takes care of all exception handling; application code can concentrate on issuing the appropriate SQL and extracting results.


-By providing a meaningful exception hierarchy for your application code to work with in place of SQLException. When Spring first obtains a connection from a DataSource it examines the metadata to determine the database product. It uses this knowledge to map SQLExceptions to the correct exception in its own hierarchy descended from org.springframework.dao.DataAccessException. Thus your code can work with meaningful exceptions, and need not worry about proprietary SQLState or error codes. Spring's data access exceptions are not JDBC-specific, so your DAOs are not necessarily tied to JDBC because of the exceptions they may throw.

Explain typical Bean life cycle in Spring Bean Factory Container.


The following steps talk about throw light on how a bean life cycle is inside a bean factory container:
  1. The bean's definition is found by the bean factory container from the XML file and instantiates the bean.
  2. The Spring framework populates all of the properties as specified in the bean definition using DI.
  3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean's ID.
  4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
  5. If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called.
  6. If an init-method is specified for the bean, it will be called.
  7. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

What are ORMs supported by Spring and how it integrates with Hibernate?

Spring framework supports the following ORMs:
-Hibernate
-TopLink
-JDO
-iBatis
-JPA
and more..
With Hibernate,Spring can be integrated in following steps:
-Wire with datasource
-Declaring Hibernate properties
-Tell Spring about the Hibernate Mapping files.

No comments:

Books

  • Hibernate in Action
  • Spring in Action