Thursday, 16 April 2009

More about ApplicationContext in Spring

While the beans package provides basic functionality for managing and manipulating beans, often in a programmatic way, the context package adds ApplicationContext, which enhances BeanFactory functionality in a more framework-oriented style.

A bean factory is fine for simple applications, but to take advantage of the full power of the Spring Framework, you’ll probably want to load your application beans using Spring’s more advanced container, the application context.

Many users will use ApplicationContext in a completely declarative fashion, not even having to create it manually, but instead relying on support classes such as ContextLoader to automatically start an ApplicationContext as part of the normal startup process of a J2EE web-app. Of course, it is still possible to programmatically create an ApplicationContext.

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:

In most cases, you’ll use the ApplicationContext, which adds more enterprise-level, J2EE functionality, such as
-> internationalization (i18n)
-> custom converters (for converting Strings to Object types)
-> event publication/notification
-> Access to resources, such as URLs and files
-> Loading of multiple (hierarchical) contexts, allowing each to be focused on one particular layer, for example the web layer of an application.

You could also implement your own ApplicationContext and add support for loading from other resources (such as a database). While many Contexts are available for loading beans, you’ll only need a few, which are listed below. The others are internal classes that are used by the framework itself.

1. ClassPathXmlApplicationContext: Loads context files from the classpath (that is, WEB-INF/classes or WEB-INF/lib for JARs) in a web application. Initializes using a

new ClassPathXmlApplicationContext(path)
where path is the path to the file. The path argument can also be a String array of paths. This is a good context for using in unit tests.

2. FileSystemXmlApplicationContext: Loads context files from the file system, which is nice for testing. Initializes using a

new FileSystemXmlApplicationContext (path)
where path is a relative or absolute path to the file. The path argument can also be a String array of paths.

3. XmlWebApplicationContext: Loads context files internally by the ContextLoaderListener, but can be used outside of it. For instance, if you are running a container that doesn’t load Listeners in the order specified in web.xml, you may have to use this in another Listener. Below is the code to use this Loader.


XmlWebApplicationContext context = new XmlWebApplicationContext();
context.setServletContext(ctx);
context.refresh();



Once you’ve obtained a reference to a context, you can get references to beans using

ctx.getBean(beanId)
You will need to cast it to a specific type, but that’s the easy part. Of the above contexts, ClassPathXmlApplicationContext is the most flexible. It doesn’t care where the files are, as long as they’re in the classpath. This allows you to move files around and simply change the classpath.


Aside from the additional functionality offered by application contexts, another big difference between an application context and a bean factory is how singleton beans are loaded. A bean factory lazily loads all beans, deferring bean creation until the getBean() method is called. An application context is a bit smarter and preloads all singleton beans upon context startup. By preloading singleton beans, you ensure that they will be ready to use when needed—your application won’t have to wait for them to be created.

Hope it will be useful...

More about BeanFactory in Spring

As its name implies, a bean factory is an implementation of the Factory design pattern. That is, it is a class whose responsibility is to create and dispense beans. 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. When a bean factory hands out objects, those objects are fully configured, are aware of their collaborating objects, and are ready to use.

BeanFactory is a workhorse that initializes beans and calls their lifecycle methods. It should be noted that most lifecycle methods only apply to singleton beans. Spring cannot manage prototype (non-singleton) lifecycles. This is because, after they’re created, prototypes are handed off to the client and the container loses track of it. For prototypes, Spring is really just a replacement for the “new” operator.

A BeanFactory is represented by the interface org.springframework.beans.factory.BeanFactory, and it is having multiple implementations. The most commonly used simple BeanFactory implementation is org.springframework.beans.factory.xml.XmlBeanFactory. (This should be qualified with the reminder that ApplicationContexts are a subclass of BeanFactory, and most users end up using XML variants of ApplicationContext).

Although for most scenarios, almost all user code managed by the BeanFactory does not have to be aware of the BeanFactory, the BeanFactory does have to be instantiated somehow. This can happen via explicit user code such as:


Resource res = new FileSystemResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);



or


ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);



or


ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml", "applicationContext-part2.xml"});
// of course, an ApplicationContext is just a BeanFactory
BeanFactory factory = (BeanFactory) appContext;




Beans are lazily loaded into bean factories, meaning that while the bean factory will immediately load the bean definitions (the description of beans and their properties), the beans themselves will not be instantiated until they are needed.


BeanDefinition includes

1. class name which is normally the actual implementation class of the bean being described in the bean definition. However, if the bean is to be constructed by calling a static factory method instead of using a normal constructor, this will actually be the class name of the factory class.

2. bean behavioral configuration elements, which state how the bean should behave in the container (i.e. prototype or singleton, autowiring mode, dependency checking mode, initialization and destruction methods)

3. constructor arguments and property values to set in the newly created bean. An example would be the number of connections to use in a bean that manages a connection pool (either specified as a property or as a constructor argument), or the pool size limit.

4. other beans a bean needs to do its work, i.e. collaborators (also specified as properties or as constructor arguments). These can also be called dependencies.

In the much more common case where the BeanFactory itself directly creates the bean by calling its constructor (equivalent to Java code calling new), the class attribute specifies the class of the bean to be constructed. In the less common case where the BeanFactory calls a static factory method on a class to create the bean, the class attribute specifies the actual class containing the static factory method. (the type of the returned bean from the static factory method may be the same class or another class entirely, it doesn't matter).

1. Bean creation via constructor

When creating a bean using the constructor approach, all normal classes are usable by Spring and compatible with Spring. That is, the class being created does not need to implement any specific interfaces or be coded in a specific fashion. Just specifying the bean class should be enough. However, depending on what type of IoC you are going to use for that specific bean, you may need a default (empty) constructor.

Note : Additionally, the BeanFactory isn't limited to just managing true JavaBeans, it is also able to manage virtually any class you want it to manage. Most people using Spring prefer to have actual JavaBeans (having just a default (no-argument) constructor and appropriate setters and getters modeled after the properties) in the BeanFactory, but it it's also possible to have more exotic non-bean-style classes in your BeanFactory. If, for example, you need to use a legacy connection pool that absolutely does not adhere to the JavaBean specification, no worries, Spring can manage it as well.

Using the XmlBeanFactory you can specify your bean class as follows:


<bean id="myBean"
class="spring.MyBean"/>




2. Bean creation via static factory method

When defining a bean which is to be created using a static factory method, along with the class attribute which specifies the class containing the static factory method, another attribute named factory-method is needed to specify the name of the factory method itself. Spring expects to be able to call this method and get back a live object, which from that point on is treated as if it had been created normally via a constructor. One use for such a bean definition is to call static factories in legacy code.

Following is an example of a bean definition which specifies that the bean is to be created by calling a factory-method. Note that the definition does not specify the type (class) of the returned object, only the class containing the factory method. In this example, createInstance must be a static method.


<bean id="myBean"
class="spring.MyBean"
factory-method="createInstance"/>




3. Bean creation via instance factory method

In a fashion similar to instantiation via a static factory method, instantiation using an instance factory method is where a non-static method of an existing bean from the container is invoked to create a new bean. To use this mechanism, the 'class' attribute must be left empty, and the 'factory-bean' attribute must specify the name of a bean in the current (or parent/ancestor) container that contains the instance method that is to be invoked to create the object. The name of the factory method itself must be set using the 'factory-method' attribute.


<!-- the factory bean, which contains a method called createInstance() -->
<bean id="serviceLocator" class="com.foo.DefaultServiceLocator">
<!-- inject any dependencies required by this locator bean -->
</bean>
<!-- the bean to be created via the factory bean -->
<bean id="exampleBean"
factory-bean="serviceLocator"
factory-method="createService"/>






To singleton or not to singleton

Beans are defined to be deployed in one of two modes: singleton or non-singleton (prototype). When a bean is a singleton, only one shared instance of the bean will be managed and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned.

The non-singleton, prototype mode of a bean deployment results in the creation of a new bean instance every time a request for that specific bean is done. This is ideal for situations where for example each user needs an independent user object or something similar.

Beans are deployed in singleton mode by default, unless you specify otherwise. Keep in mind that by changing the type to non-singleton (prototype), each request for a bean will result in a newly created bean and this might not be what you actually want. So only change the mode to prototype when absolutely necessary.

In the example below, two beans are declared of which one is defined as a singleton, and the other one is a non-singleton (prototype). myBean is created each and every time a client asks the BeanFactory for this bean, while myBeanAgain is only created once; a reference to the exact same instance is returned on each request for this bean.


<bean id="myBean"
class="spring.MyBean" singleton="false"/>
<bean name="myBeanAgain"
class="spring.MyBeanAgain" singleton="true"/>




A BeanFactory is essentially nothing more than the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies. The BeanFactory enables you to read bean definitions and access them using the bean factory. When using just the BeanFactory you would create one and read in some bean definitions in the XML format as follows:


InputStream is = new FileInputStream("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(is);





The BeanFactory interface has only five methods for clients to call:

boolean containsBean(String): returns true if the BeanFactory contains a bean definition or bean instance that matches the given name

Object getBean(String): returns an instance of the bean registered under the given name. Depending on how the bean was configured by the BeanFactory configuration, either a singleton and thus shared instance or a newly created bean will be returned. A BeansException will be thrown when either the bean could not be found (in which case it'll be a NoSuchBeanDefinitionException), or an exception occurred while instantiating and preparing the bean

Object getBean(String,Class): returns a bean, registered under the given name. The bean returned will be cast to the given Class. If the bean could not be cast, corresponding exceptions will be thrown (BeanNotOfRequiredTypeException). Furthermore, all rules of the getBean(String) method apply (see above)

boolean isSingleton(String): determines whether or not the bean definition or bean instance registered under the given name is a singleton or a prototype. If no bean corresponding to the given name could not be found, an exception will be thrown (NoSuchBeanDefinitionException)

String[] getAliases(String): Return the aliases for the given bean name, if any were defined in the bean definition

Hope it will be useful.....

Tuesday, 14 April 2009

BeanFactory and ApplicationContext in Spring

Basis for Spring's Dependency Injection feature is provided by two most fundamental and important packages in Spring namely org.springframework.beans and org.springframework.context packages.

The BeanFactory from org.springframework.beans provides an advanced configuration mechanism capable of managing beans (objects) of any nature, using potentially any kind of storage facility.

The ApplicationContext from org.springframework.context package 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.

BeanFactory is an internal interface that provides the configuration framework and basic functionality, while the ApplicationContext adds enhanced capabilities to it, some of them perhaps more J2EE and enterprise-centric.

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.

How to determine which one is best suited in a particular situation. BeanFactory or ApplicationContext???

Normally when building most applications in a J2EE-environment, the best option is to use the application context for every application unless the resources of this application are restricted, such as when running in an applet or a mobile device, and you don't need all the features of the ApplicationContext.


Hope it will be useful...

Sunday, 12 April 2009

Dependency Injection in Spring

What is Dependency Injection:

Originally, dependency injection was commonly referred to by another name inversion of control(IoC). But in an article written in early 2004,
Martin Fowler asked what aspect of control is being inverted. He concluded that it is the acquisition of dependencies that is being inverted.

In the Java community there's been a rush of lightweight containers that help to assemble components from different projects into a cohesive application.(Ex: Spring) Underlying these containers is a common pattern to how they perform the wiring, a concept they refer under the very generic name of "Inversion of Control"

For this new breed of containers the inversion is about how they lookup a plugin implementation. The approach that these containers use is to ensure that any user of a plugin follows some convention that allows a separate assembler module to inject the implementation into the lister.

Based on that revelation, he coined the phrase “dependency injection,” a term that better describes what is going on. Inversion of Control is a generic term and the more specific name for this pattern is Dependency Injection.

Dependency injection is basically giving an object what it needs instead of letting this object get it by itself. It is based on a best practice technique (design pattern). This technique allows a part of application to be changed without causing problems in other areas of the application. A design is inflexible unless it cannot be easily adapted.

Why use Dependency Injection:

Instead of using Depenedency Injection if we hardcode "new" in our code.
What if something changes?
How do we externalize configuration from Java code, important if things change?

By avoiding use of a custom factory we are reducing extra code to be written in the application

By applying Dependency Injection in your projects, you’ll find that your code will become significantly simpler, easier to understand, and easier to test.

Any nontrivial application is made up of two or more classes that collaborate with each other to perform some business logic. Traditionally,
each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). This can lead to highly coupled and hard-to-test code. When applying Dependency injection(DI), objects are given their dependencies at creation time by some external entity that coordinates each object in the system. In other words, dependencies are injected into objects. So, DI means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

Software components (Clients), are often a part of a set of collaborating components which depend upon other components (Services) to successfully complete their intended purpose. In many scenarios, they need to know “which” components to communicate with, “where” to locate them, and “how” to communicate with them. When the way such services can be accessed is changed, such changes can potentially require the source of lot of clients to be changed.

One way of structuring the code is to let the clients embed the logic of locating and/or instantiating the services as a part of their usual logic. Another way to structure the code is to have the clients declare their dependency on services, and have some "external" piece of code assume the responsibility of locating and/or instantiating the services and simply supplying the relevant service references to the clients when needed. In the latter method, client code typically is not required to be changed when the way to locate an external dependency changes. This type of implementation is considered to be an implementation of Dependency Injection and the "external" piece of code referred to earlier is likely to be either hand coded or implemented using one of a variety of DI frameworks.

Dependency Injection uses the Hollywood Principle: “Don’t call me, I’ll call you.” In other words, your classes don’t look up or instantiate the classes they depend on. The control is inverted and some form of container sets the dependencies. Using IoC often leads to much cleaner code and provides an excellent way to de-couple dependent classes.

IOC in Spring:

IoC is a big part of what Spring does. It also offers a number of other capabilities apart from Dependency Injection(DI).

The core of Spring’s implementation is based on DI, although dependency lookup features are provided as well. When Spring automatically provides collaborators to a dependent object, it does so using DI. In a Spring-based application, it is always preferable to use dependency injection to pass collaborators to dependent objects rather than have the dependent objects obtain the collaborators via lookup. Although DI is the preferred mechanism for wiring together collaborators and dependent objects, you need dependency
lookup to access the dependent objects. In many environments, Spring cannot automatically wire up all of your application components using DI, and you must use dependency lookup to access the initial set of components. When you are building web applications using Spring’s MVC
support, Spring can avoid this by gluing your entire application together automatically. Wherever possible, you should use DI with Spring; otherwise, you can fall back on the dependency lookup capabilities.

Dependency Injection(DI) is provided by Core package in Spring Framework allowing you to manage bean container functionality. The basic principle is that beans define their dependencies (i.e. the other objects they work with) only through constructor arguments, arguments to a factory method, or properties which are set on the object instance after it has been constructed or returned from a factory method. Then, it is the job of the container to actually inject those dependencies when it creates the bean. This is fundamentally the inverse (hence the name Inversion of Control) of the bean instantiating or locating its dependencies on its own using direct construction of classes, or something like the Service Locator pattern.

An interesting feature of Spring’s IoC container is that it has the ability to act as an adaptor between its own dependency injection container and external dependency lookup containers.

Spring supports both constructor and setter injection and bolsters the standard IoC feature set with a whole host of useful additions to make your life easier.

Dependency Injection majorly in two forms:

1. Setter-based: Classes are typically JavaBeans, with a no-arg constructor, and with setters for the IoC container to use when wiring dependencies. This is the variant recommended by Spring. While Spring supports constructor-based injection, a large number of constructor arguments can be difficult to manage.


public interface Hello {

public String sayHello(String str);

public String showEmpDetails();
}

public class HelloImpl implements Hello{

private String greeting;
private EmployeeTO empTO;

public String sayHello(String str){
return greeting+" "+str;
}

public String showEmpDetails(){
return "Employee "+empTO.getName()+ " with empId = "+empTO.getId();
}

public String getGreeting() {
return greeting;
}

public void setGreeting(String greeting) {
System.out.println("Inside setGreeting");
this.greeting = greeting;
}

public void setEmpTO(EmployeeTO empTO) {
System.out.println("Inside setEmpTO");
this.empTO = empTO;
}

}

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="hello" class="bean_injection.HelloImpl">

<property name="greeting">
<value>Good Night!...</value>
</property>

<property name="empTO">
<ref local="employeeTO"/>
</property>

</bean>

<bean id="employeeTO" class="bean_injection.EmployeeTO">

<property name="id">
<value>1</value>
</property>

<property name="name">
<value>Prashant</value>
</property>

</bean>


</beans>




2. Constructor-based: Classes contain constructors with a number of arguments. The IoC container discovers and invokes the constructor based on the number of arguments and their object types. This approach guarantees that a bean is not created in an invalid state.


public interface Hello {

public String sayHello(String str);
}

public class HelloImpl implements Hello{

private String greeting;

public HelloImpl(){}

public HelloImpl(String str){
System.out.println("Inside constructor ");
this.greeting = str;
}

public String sayHello(String str){
return greeting+" "+str;
}

}

<beans>

<bean id="hello" class="bean_injection.HelloImpl">

<constructor-arg>
<value>Good Morning!...</value>
</constructor-arg>
</bean>

</beans>




Which one to use (Setter-based / Constructor-based)?

Constructor injection is particularly useful when you absolutely must have an instance of the dependency class before your component is used. Many containers, Spring included, provide a mechanism for ensuring that all dependencies are defined when you use setter injection, but by using constructor injection, you assert the requirement for the dependency in a container-agnostic manner.

Setter injection is useful in a variety of different cases. If you want the component to expose its dependencies to the container but provide its own defaults, setter injection is usually the best way to accomplish this. Another benefit of setter injection is that it allows dependencies to be declared on an interface, although this is not as useful as you might first think. Consider a typical business
interface with one business method, defineMeaningOfLife(). If, in addition to this method, you define a setter for injection such as setEncylopedia(), you are mandating that all implementations must use or at least be aware of the encyclopedia dependency. You do not need to define this setter at all—any decent IoC container, Spring included, can work with the component in terms of the
business interface but still provide the dependencies of the implementing class.

Benefits of Dependency Injection :

1. Unit testable
2. Dependencies are explicit
3. Consistent
4. Can wire up arbitrarily complicated graphs
5. You don’t need to write plumbing code
6. Pluggability
7. Reduces cost of programming to interfaces to zero

As described by Rod Johnson "Spring provides a factory to end all factories".

Hope it will be useful.