Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Saturday, May 1, 2010

Bean Scope

Bean scopes

When you create a bean definition what you are actually creating is a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, just like a class, you can potentially have many object instances created from a single recipe.

You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration instead of having to 'bake in' the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports exactly five scopes (of which three are available only if you are using a web-awareApplicationContext).

The scopes supported out of the box are listed below:

Scope Description

singleton Scopes a single bean definition to a single object instance per Spring IoC container.


prototype Scopes a single bean definition to any number of object instances.


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.


reference

http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-factory-scopes




Sunday, February 1, 2009

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:
The bean's definition is found by the bean factory container from the XML file and instantiates the bean.
The Spring framework populates all of the properties as specified in the bean definition using DI.
If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean's ID.
If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called.
If an init-method is specified for the bean, it will be called.
Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

JDBC Problems 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.

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.

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.

Monday, January 26, 2009

Explain DI or IOC pattern

Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC. Dependancy Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor instead of creating one internally. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected, rather it is a provider of some capability or resource that is injected. There are three common forms of dependency injection: setter-, constructor- and interface-based injection. Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.

Spring Features

Spring is a layered Java/J2EE application platform,

Spring includes:

  • The most complete lightweight container, providing centralized, automated configuration and wiring of your application objects. The container is non-invasive, capable of assembling a complex system from a set of loosely-coupled components (POJOs) in a consistent and transparent fashion. The container brings agility and leverage, and improves application testability and scalability by allowing software components to be first developed and tested in isolation, then scaled up for deployment in any environment (J2SE or J2EE).

  • A common abstraction layer for transaction management, allowing for pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Generic strategies for JTA and a single JDBC DataSource are included. In contrast to plain JTA or EJB CMT, Spring's transaction support is not tied to J2EE environments.

  • A JDBC abstraction layer that offers a meaningful exception hierarchy (no more pulling vendor codes out of SQLException), simplifies error handling, and greatly reduces the amount of code you'll need to write. You'll never need to write another finally block to use JDBC again. The JDBC-oriented exceptions comply to Spring's generic DAO exception hierarchy.

  • Integration with Toplink, Hibernate, JDO, and iBATIS SQL Maps: in terms of resource holders, DAO implementation support, and transaction strategies. First-class Hibernate support with lots of IoC convenience features, addressing many typical Hibernate integration issues. All of these comply to Spring's generic transaction and DAO exception hierarchies.

  • AOP functionality, fully integrated into Spring configuration management. You can AOP-enable any object managed by Spring, adding aspects such as declarative transaction management. With Spring, you can have declarative transaction management without EJB... even without JTA, if you're using a single database in Tomcat or another web container without JTA support.

  • A flexible 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. Note that a Spring middle tier can easily be combined with a web tier based on any other web MVC framework, like Struts, WebWork, or Tapestry.