Introduction To Spring Framework: by Akhilesh Jaiswal

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 25

Introduction to Spring framework

By Akhilesh Jaiswal

Spring
Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.

Why use Spring

Wiring of components (Dependency Injection)


Declarative programming without J2EE

Easily configured aspects, esp. transaction support

Conversion of checked exceptions to unchecked Not an all-or-nothing solution

Extremely modular and flexible

Well designed

Easy to extend Many reusable classes

Spring Framework

The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an applications configuration and dependency specification from the actual application code.
Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components. Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAOs JDBC-oriented exceptions comply to its generic DAO exception hierarchy.

Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Springs generic transaction and DAO exception hierarchies.
Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality. Spring Web module: The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects. Spring MVC framework: The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.

Spring Application

What does Spring offer

Dependency Injection

Also known as IoC (Inversion of Control)


Runtime injection-based The rest of spring

Aspect Oriented Programming

Portable Service Abstractions

ORM, DAO, Web MVC, Web, etc. Allows access to these without knowing how they actually work

Dependency Injection

The basic concept of the dependency injection (also known as Inversion of Control) 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. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

Types of Dependency injection

Constructor Injection (e.g. Pico container, Spring etc):


Dependencies are provided as constructor parameters.

Setter Injection (e.g. Spring): Dependencies are assigned through


JavaBeans properties (ex: setter methods).

Interface Injection (e.g. Avalon): Injection is done through an


interface.

Note: Spring supports Constructor and Setter Injection only.

Constructor Injection

For constructor injection, we use constructor with parameters as shown below,

public class namebean { String name; public namebean(String a) { name = a; } } We will set the property 'name' while creating an instance of the bean 'namebean' as namebean bean1 = new namebean("tom");
Here we use the <constructor-arg> element to set the the property by constructor injection as <bean id="bean1" class="namebean"> <constructor-arg> <value>My Bean Value</value> </constructor-arg> </bean>

Setter Injection

Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows: public class namebean { String name; public void setName(String a) { name = a; } public String getName() { return name; } } We will create an instance of the bean 'namebean' (say bean1) and set property as bean1.setName("tom"); Here in setter injection, we will set the property 'name' in spring configuration file as showm below: <bean id="bean1" class="namebean"> <property name="name" > <value>tom</value> </property> </bean> The subelement <value> sets the 'name' property by calling the set method as setName("tom"); This process is called setter injection. To set properties that reference other beans <ref>, subelement of <property> is used as shown below, <bean id="bean1" class="bean1impl"> <property name="game"> <ref bean="bean2"/> </property> </bean> <bean id="bean2" class="bean2impl" />

BeanFactory

Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. As the bean factory knows about many objects within an application, it is able to create association between collaborating objects as they are instantiated. This removes the burden of configuration from the bean and the client. There are several implementation of BeanFactory. The most useful one is "org.springframework.beans.factory.xml.XmlBeanFactory" It loads its beans based on the definition contained in an XML file. To create an XmlBeanFactory, pass a InputStream to the constructor. The resource will provide the XML to the factory. BeanFactory factory = new XmlBeanFactory(new FileInputStream("myBean.xml"));

This line tells the bean factory to read the bean definition from the XML file. The bean definition includes the description of beans and their properties. But the bean factory doesn't instantiate the bean yet. To retrieve a bean from a 'BeanFactory', the getBean() method is called. When getBean() method is called, factory will instantiate the bean and begin setting the bean's properties using dependency injection. myBean bean1 = (myBean)factory.getBean("myBean");

Bean Creation

Direct instantiation

<bean id=beanId class=className>


Same syntax but class is subclass of BeanFactory getObject() called to obtain Bean <bean id=beanId class=className" factory-method=" staticCreationMethod>

BeanFactory instantiation

Static Factory

Instance Factory Method

<bean id=beanId factory-bean=existingBeanId" factorymethod=nonStaticCreationMethod">

Beans may be singletons or prototypes

Attribute singleton=false causes instantiation with each getBean() lookup Singleton is default May be overridden on per-instance basis by lazy-init=true

XmlBeanFactory pre-instantiates singletons

Beans may also be marked abstract, allowing reuse of attribute values through inheritance

Autowiring Properties

Beans may be auto-wired (rather than using <ref>)


Per-bean attribute autowire Explicit settings override Bean identifier matches property name Type matches other defined bean Match constructor argument types Attempt by constructor, otherwise type

autowire=name

autowire=type

autowire=constructor

autowire=autodetect

Dependency Checking

Ensures properties are defined Per-bean attribute dependency-check None required by default Verifies autowiring succeeded simple all but collaborators object collaborators only all Collaborators, primitive types, and collections

Lifecycle Customization

Can define init method called after properties set

init-method=<method-name>
destroy-method=<method-name>

Can define destroy method as shutdown hook

May alternatively implement InitializingBean and/or DisposableBean

At cost of Spring dependency

BeanFactory Usage
InputStream is = new FileInputStream("beans.xml"); XmlBeanFactory factory = new XmlBeanFactory(is); MyBeanClass bean = (MyBeanClass)factory.getBean(myBean);

OR
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); MyBeanClass bean = (MyBeanClass)ctx.getBean(myBean);

ApplicationContext

Extends functionality of BeanFactory Pre-instantiates singleton beans Detects and registers BeanPostProcessors and BeanFactoryPostProcessors Supports nesting of contexts ApplicationListener and ApplicationEvents

Initialized and closed predefined Custom may be created

MessageSource provides i18n messaging


<bean id=messageSource class=...ResourceBundleMessageSource/> Contains list of bundle base names

Web Initialization

Web applications may use ContextLoaderListener to initialize Spring

web.xml

web.xml <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/daoContext.xml /WEBINF/applicationContext.xml </param-value> </context-param>


<listener> <listenerclass>org.springframework.web.context.ContextLoaderListener</listenerclass> </listener>

Specialized Beans

MethodInvokingFactoryBean

Invokes method on registered beans or any static methods Stores return value

SingletonBeanFactoryLocator and ContextSingletonBeanFactoryLocator


Useful for sharing BeanFactories Eliminate duplication of beans in multiple similar factories or contexts

ApplicationContext Example
<bean id="propertyConfigurer"

class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <property name="location"><value>database.properties</value></property> </bean>


<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>${database.connection.driver_class}</value> </property> <property name="url"> <value>${database.connection.url}</value> </property> </bean>

Benefits of Dependency Injection

Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration. Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test. Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own. IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.

You might also like