Category Archives: Uncategorized

Spring Framework- My way

Contents

 

1.   What is Spring framework?

The Spring Framework is an open source application framework and inversion of control container for the Java platform. It is lightweight when it comes to size and transparency.

2.   Spring web MVC framework

The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.

  • The Model encapsulates the application data and in general they will consist of POJO.
  • The View is responsible for rendering the model data and in general it generates HTML output that the client’s browser can interpret.
  • The Controller is responsible for processing user requests and building appropriate model and passes it to the view for rendering.

2.1.The DispatcherServlet

The Spring Web model-view-controller (MVC) framework is designed around  DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram:

Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet:

  • After receiving an HTTP request, DispatcherServlet consults the HandlerMappingto call the appropriate Controller.
  • The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.
  • The DispatcherServletwill take help from ViewResolver to pick up the defined view for the request.
  • Once view is finalized, The DispatcherServletpasses the model data to the view which is finally rendered on the browser.

All the above mentioned components i.e. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext which is an extension of the plain ApplicationContext with some extra features necessary for web applications.

3.   Overview of Spring framework

3.1.Dependency injection and Inversion of Control

IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies, i.e. the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.

3.2.Modules

The Spring Framework consists of features organized into about 20 modules. These modules are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming),

Instrumentation, Messaging, and Test, as shown in the following diagram.

3.3.Core Container

The Core Container consists of the spring-core, spring-beans, spring-context,

springcontext-support, and spring-expression (Spring Expression Language) modules.

 

The spring-core and spring-beans modules provide the fundamental parts of the framework including the IoC and Dependency Injection features. The BeanFactory is a sophisticated implementation of the factory pattern. It removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic.

The Context (spring-context) module builds on the solid base provided by the Core and Beans modules. The ApplicationContext interface is the focal point of the Context module.

3.4.Web

The Web layer consists of the spring-web, spring-webmvc, spring-websocket, and

springwebmvc-portlet modules.

 

The spring-web module provides basic web-oriented integration features such as multipart file upload functionality and the initialization of the IoC container using Servlet listeners and a web-oriented application context. It also contains an HTTP client and the web-related parts of Spring’s remoting support.

The spring-webmvc module (also known as the Web-Servlet module) contains Spring’s

modelview-controller (MVC) and REST Web Services implementation for web applications. Spring’s MVC framework provides a clean separation between domain model code and web forms and integrates with all of the other features of the Spring Framework.

The spring-webmvc-portlet module (also known as the Web-Portlet module) provides the MVC implementation to be used in a Portlet environment and mirrors the functionality of the

spring-webmvc module.

 

3.5.Usage Scenarios

The building blocks described previously make Spring a logical choice in many scenarios, from embedded applications that run on resource-constrained devices to full-fledged enterprise applications that use Spring’s transaction management functionality and web framework integration.

Existing front-ends built with Struts, Tapestry, JSF or other UI frameworks can be integrated with a Springbased middle-tier, which allows you to use Spring transaction features. You simply need to wire up your business logic using an ApplicationContext and use a WebApplicationContext to integrate your web layer.

 

 

4.   Core Technologies

4.1. The IoC container

Refer Dependency injection and Inversion of Control

The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework’s IoC container. The BeanFactory provides the configuration framework and basic functionality, while the ApplicationContext adds more enterprise-centric functionality to it. The ApplicationContext is a complete superset of the BeanFactory, and any description of BeanFactory capabilities and behavior is to be considered to apply to the ApplicationContext as well.

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.

4.1.1. Container overview

The interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata. The configuration metadata is represented in XML, Java annotations, or Java code. It allows you to express the objects that compose your application and the rich interdependencies between such objects.

The following diagram is a high-level view of how Spring works. Your application classes are combined with configuration metadata so that after the ApplicationContext is created and initialized, you have a fully configured and executable system or application.

 

As the preceding diagram shows, the Spring IoC container consumes a form of configuration metadata; this configuration metadata represents how you as an application developer tell the Spring container to instantiate, configure, and assemble the objects in your application. Configuration metadata is traditionally supplied in a simple and intuitive XML format, which is what most of this chapter uses to convey key concepts and features of the Spring IoC container. However XML-based metadata is not the only allowed form of configuration metadata, others include Annotation-based configuration, Java-Based configuration.

The following example shows the basic structure of XML-based configuration metadata:

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=http://www.springframework.org/schema/beans&#8221;

xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221;

xsi:schemaLocation=http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd&#8221;>

<bean id=“…” class=“…”>

<!– collaborators and configuration for this bean go here –>

</bean>

<bean id=“…” class=“…”>

<!– collaborators and configuration for this bean go here –>

</bean>

<!– more bean definitions go here –>

</beans>

The id attribute is a string that you use to identify the individual bean definition. The class attribute defines the type of the bean and uses the fully qualified classname. The value of the id attribute refers to collaborating objects.

4.1.2.   Instantiating a container

Instantiating a Spring IoC container is straightforward. The location path or paths supplied to an ApplicationContext constructor are actually resource strings that allow the container to load configuration metadata from a variety of external resources such as the local file system, from the Java CLASSPATH, and so on.

ApplicationContext context =

new ClassPathXmlApplicationContext(new String[] {“services.xml”, “daos.xml”});

It can be useful to have bean definitions span multiple XML files. Often each individual XML configuration file represents a logical layer or module in your architecture. You can use the application context constructor to load bean definitions from all these XML fragments. This constructor takes multiple Resource locations, as was shown in the previous section. Alternatively, use one or more occurrences of the <import/> element to load bean definitions from another file or files.

<beans>

<import resource=“services.xml”/>

<import resource=“resources/messageSource.xml”/>

<import resource=“/resources/themeSource.xml”/>

<bean id=“bean1” class=“…”/>

<bean id=“bean2” class=“…”/>

</beans>

 

 

4.1.3.   Using the container

The ApplicationContext is the interface for an advanced factory capable of maintaining a registry of different beans and their dependencies. Using the method T getBean(String name, Class<T> requiredType) you can retrieve instances of your beans. The ApplicationContext enables you to read bean definitions and access them as follows:

// create and configure beans

ApplicationContext context =

new ClassPathXmlApplicationContext(new String[] {“services.xml”, “daos.xml”});

// retrieve configured instance

PetStoreService service = context.getBean(“petStore”, PetStoreService.class);

// use configured instance

List<String> userList = service.getUsernameList();

 

You use getBean() to retrieve instances of your beans. The ApplicationContext interface has a few other methods for retrieving beans, but ideally your application code should never use them. Indeed, your application code should have no calls to the getBean() method at all, and thus no dependency on Spring APIs at all. For example, Spring’s integration with web frameworks provides for dependency injection for various web framework classes such as controllers and JSF-managed beans.

4.1.4.   Bean overview

A Spring IoC container manages one or more beans. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions. Within the container itself, these bean definitions are represented as BeanDefinition objects, which contain (among other information) the following metadata:

  • A package-qualified class name: typically the actual implementation class of the bean being defined.
  • Bean behavioral configuration elements, which state how the bean should behave in the container (scope, lifecycle callbacks, and so forth).
  • References to other beans that are needed for the bean to do its work; these references are also called collaborators or dependencies.
  • Other configuration settings to set in the newly created object, for example, the number of connections to use in a bean that manages a connection pool, or the size limit of the pool.

4.1.5.   Instantiating beans

A bean definition essentially is a recipe for creating one or more objects. The container looks at the recipe for a named bean when asked, and uses the configuration metadata encapsulated by that bean definition to create (or acquire) an actual object.

If you use XML-based configuration metadata, you specify the type (or class) of object that is to be instantiated in the class attribute of the <bean/> element. This class attribute, which internally is a Class property on a BeanDefinition instance, is usually mandatory. You use the Class property in one of two ways:

  • Typically, to specify the bean class to be constructed in the case where the container itself directly creates the bean by calling its constructor reflectively, somewhat equivalent to Java code using the new
  • To specify the actual class containing the static factory method that will be invoked to create the object, in the less common case where the container invokes a static factory method on a class to create the bean. The object type returned from the invocation of the static factory method may be the same class or another class entirely.

·  Instantiation with a constructor

When you create a bean by the constructor approach, all normal classes are usable by and compatible with Spring. That is, the class being developed does not need to implement any specific interfaces or to be coded in a specific fashion. Simply specifying the bean class should suffice.

With XML-based configuration metadata you can specify your bean class as follows:

<bean id=“exampleBean” class=“examples.ExampleBean”/>

<bean name=“anotherExample” class=“examples.ExampleBeanTwo”/>

·  Instantiation with a static factory method

When defining a bean that you create with a static factory method, you use the class attribute to specify the class containing the static factory method and an attribute named factory-method to specify the name of the factory method itself.

The following bean definition specifies that the bean will be created by calling a factory-method. The definition does not specify the type (class) of the returned object, only the class containing the factory method. In this example, the createInstance() method must be a static method.

<bean id=“clientService”

class=“examples.ClientService”

factory-method=“createInstance”/>

 

public class ClientService {

private static ClientService clientService = new ClientService();

private ClientService() {}

public static ClientService createInstance() {

return clientService;

}

}

·  Instantiation using an instance factory method

Similar to instantiation through a static factory method, instantiation with an instance factory method invokes a non-static method of an existing bean from the container to create a new bean. To use this mechanism, leave the class attribute empty, and in the factory-bean attribute, 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. Set the name of the factory method itself with the factory-method attribute.

<!– the factory bean, which contains a method called createInstance() –>

<bean id=“serviceLocator” class=“examples.DefaultServiceLocator”>

<!– inject any dependencies required by this locator bean –>

</bean>

<!– the bean to be created via the factory bean –>

<bean id=“clientService”

factory-bean=“serviceLocator”

factory-method=“createClientServiceInstance”/>

 

public class DefaultServiceLocator {

private static ClientService clientService = new ClientServiceImpl();

private DefaultServiceLocator() {}

public ClientService createClientServiceInstance() {

return clientService;

}

}

One factory class can also hold more than one factory method as shown here:

<bean id=“serviceLocator” class=“examples.DefaultServiceLocator”>

<!– inject any dependencies required by this locator bean –>

</bean>

<bean id=“clientService”

factory-bean=“serviceLocator”

factory-method=“createClientServiceInstance”/>

<bean id=“accountService”

factory-bean=“serviceLocator”

factory-method=“createAccountServiceInstance”/>

 

public class DefaultServiceLocator {

private static ClientService clientService = new ClientServiceImpl();

private static AccountService accountService = new AccountServiceImpl();

private DefaultServiceLocator() {}

public ClientService createClientServiceInstance() {

return clientService;

}

public AccountService createAccountServiceInstance() {

return accountService;

}

}

4.1.6.   Dependencies

A typical enterprise application does not consist of a single object (or bean in the Spring parlance). Even the simplest application has a few objects that work together to present what the end-user sees as a coherent application.

·  Dependency injection

Refer Dependency injection and Inversion of Control

DI exists in two major variants, Constructor-based dependency injection and Setter-based dependency injection.

ü Constructor-based dependency injection

Constructor-based DI is accomplished by the container invoking a constructor with a number of arguments, each representing a dependency. Calling a static factory method with specific arguments to construct the bean is nearly equivalent, and this discussion treats arguments to a constructor and to a static factory method similarly.

public class SimpleMovieLister {

// the SimpleMovieLister has a dependency on a MovieFinder

private MovieFinder movieFinder;

// a constructor so that the Spring container can inject a MovieFinder

public SimpleMovieLister(MovieFinder movieFinder) {

this.movieFinder = movieFinder;

}

// business logic that actually uses the injected MovieFinder is omitted…

}

ü Setter-based dependency injection

Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

public class SimpleMovieLister {

// the SimpleMovieLister has a dependency on the MovieFinder

private MovieFinder movieFinder;

// a setter method so that the Spring container can inject a MovieFinder

public void setMovieFinder(MovieFinder movieFinder) {

this.movieFinder = movieFinder;

}

// business logic that actually uses the injected MovieFinder is omitted…

}

 

The ApplicationContext supports constructor-based and setter-based DI for the beans it manages. It also supports setter-based DI after some dependencies have already been injected through the constructor approach. You configure the dependencies in the form of a BeanDefinition, which you use in conjunction with PropertyEditor instances to convert properties from one format to another.

·  Dependency resolution process

The container performs bean dependency resolution as follows:

  • The ApplicationContext is created and initialized with configuration metadata that describes all the beans. Configuration metadata can be specified via XML, Java code, or annotations.
  • For each bean, its dependencies are expressed in the form of properties, constructor arguments, or arguments to the static-factory method if you are using that instead of a normal constructor. These dependencies are provided to the bean, when the bean is actually created.
  • Each property or constructor argument is an actual definition of the value to set, or a reference to another bean in the container.
  • Each property or constructor argument which is a value is converted from its specified format to the actual type of that property or constructor argument. By default Spring can convert a value supplied in string format to all built-in types, such as int, long, String, boolean, etc.

The Spring container validates the configuration of each bean as the container is created. However, the bean properties themselves are not set until the bean is actually created. Beans that are singleton-scoped and set to be pre-instantiated (the default) are created when the container is created.

·  Examples of dependency injection

The following example uses XML-based configuration metadata for setter-based DI.

<bean id=“exampleBean” class=“examples.ExampleBean”>

<!– setter injection using the nested ref element –>

<property name=“beanOne”>

<ref bean=“anotherExampleBean”/>

</property>

<!– setter injection using the neater ref attribute –>

<property name=“beanTwo” ref=“yetAnotherBean”/>

<property name=“integerProperty” value=“1”/>

</bean>

 

<bean id=“anotherExampleBean” class=“examples.AnotherBean”/>

<bean id=“yetAnotherBean” class=“examples.YetAnotherBean”/>

 

public class ExampleBean {

private AnotherBean beanOne;

private YetAnotherBean beanTwo;

private int i;

public void setBeanOne(AnotherBean beanOne) {

this.beanOne = beanOne;

}

public void setBeanTwo(YetAnotherBean beanTwo) {

this.beanTwo = beanTwo;

}

public void setIntegerProperty(int i) {

this.i = i;

}

}

The following example uses constructor-based DI:

<bean id=“exampleBean” class=“examples.ExampleBean”>

<!– constructor injection using the nested ref element –>

<constructor-arg>

<ref bean=“anotherExampleBean”/>

</constructor-arg>

<!– constructor injection using the neater ref attribute –>

<constructor-arg ref=“yetAnotherBean”/>

<constructor-arg type=“int” value=“1”/>

</bean>

<bean id=“anotherExampleBean” class=“examples.AnotherBean”/>

<bean id=“yetAnotherBean” class=“examples.YetAnotherBean”/>

 

public class ExampleBean {

private AnotherBean beanOne;

private YetAnotherBean beanTwo;

private int i;

public ExampleBean(

AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {

this.beanOne = anotherBean;

this.beanTwo = yetAnotherBean;

this.i = i;

}

}

Now consider a variant of this example, where instead of using a constructor, Spring is told to call a static factory method to return an instance of the object:

<bean id=“exampleBean” class=“examples.ExampleBean” factory-method=“createInstance”>

<constructor-arg ref=“anotherExampleBean”/>

<constructor-arg ref=“yetAnotherBean”/>

<constructor-arg value=“1”/>

</bean>

<bean id=“anotherExampleBean” class=“examples.AnotherBean”/>

<bean id=“yetAnotherBean” class=“examples.YetAnotherBean”/>

 

public class ExampleBean {

// a private constructor

private ExampleBean(…) {

}

// a static factory method; the arguments to this method can be

// considered the dependencies of the bean that is returned,

// regardless of how those arguments are actually used.

public static ExampleBean createInstance (

AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {

ExampleBean eb = new ExampleBean (…);

// some other operations…

return eb;

}

}