Spring Framework

30
An Introduction to the An Introduction to the Spring Framework Spring Framework

description

Introduction to SPRING FRAMEWORK

Transcript of Spring Framework

Page 1: Spring Framework

An Introduction to theAn Introduction to the Spring Spring FrameworkFramework

Page 2: Spring Framework

What is the Spring What is the Spring Framework?Framework?

Spring is a Lightweight Spring is a Lightweight ApplicationApplication Framework Framework

Where Struts, WebWork and others Where Struts, WebWork and others can be considered can be considered Web Web frameworks, frameworks, Spring addresses all tiers of an Spring addresses all tiers of an applicationapplication

Spring provides the plumbing so that Spring provides the plumbing so that you don’t have to!you don’t have to!

Page 3: Spring Framework

Spring == J2EE Application Spring == J2EE Application Server?Server?

Spring is NOT a J2EE application Spring is NOT a J2EE application serverserver

Spring can integrate nicely with J2EE Spring can integrate nicely with J2EE application servers (or any Java application servers (or any Java environment)environment)

Spring can, in many cases, elegantly Spring can, in many cases, elegantly replace services traditionally replace services traditionally provided by J2EE application serversprovided by J2EE application servers

Page 4: Spring Framework

Before StrutsBefore Struts

Before Struts, everyone wrote their own front Before Struts, everyone wrote their own front controllers or put their controller logic in JSPcontrollers or put their controller logic in JSP

After Struts, the custom front controllers After Struts, the custom front controllers could be thrown outcould be thrown out Developers focus on solving business problemsDevelopers focus on solving business problems Productivity Gain!Productivity Gain!

But with Struts (and most of the other web But with Struts (and most of the other web frameworks) you still have to write your own frameworks) you still have to write your own business delegates or service layers…business delegates or service layers…

Page 5: Spring Framework

Spring Can Help!Spring Can Help! Spring brings a consistent structure to your entire Spring brings a consistent structure to your entire

applicationapplication Spring provides a consistent way to glue your whole Spring provides a consistent way to glue your whole

application togetherapplication together Spring provides elegant integration points with standard Spring provides elegant integration points with standard

interfacesinterfaces HibernateHibernate JDOJDO TopLinkTopLink EJBEJB RMIRMI JNDIJNDI JMSJMS Web ServicesWeb Services Struts etc.Struts etc.

Page 6: Spring Framework

ContCont Just as Struts did on the web tier, we can Just as Struts did on the web tier, we can

realize huge productivity gains by not realize huge productivity gains by not having to write the common integration having to write the common integration points across your applicationpoints across your application

Page 7: Spring Framework

The Spring Framework Mission The Spring Framework Mission StatementStatement

J2EE should be easier to useJ2EE should be easier to use It's best to program to interfaces, rather than It's best to program to interfaces, rather than

classes. Spring reduces the complexity cost of classes. Spring reduces the complexity cost of using interfaces to zero.using interfaces to zero.

JavaBeans offer a great way of configuring JavaBeans offer a great way of configuring applications.applications.

OO design is more important than any OO design is more important than any implementation technology, such as J2EE.implementation technology, such as J2EE.

Testability is essential, and a framework such as Testability is essential, and a framework such as Spring should help make your code easier to test.Spring should help make your code easier to test.

Page 8: Spring Framework

Spring Framework Mission Spring Framework Mission Statement (continued)Statement (continued)

Your application code should Your application code should notnot depend on Spring APIsdepend on Spring APIs

Spring should not compete with good Spring should not compete with good existing solutions, but Used for existing solutions, but Used for integration. (For example, JDO and integration. (For example, JDO and Hibernate are great O/R mapping Hibernate are great O/R mapping solutions. We don't need to develop solutions. We don't need to develop another one.)another one.)

Page 9: Spring Framework

Spring ArchitectureSpring Architecture

Page 10: Spring Framework

Spring is Non-InvasiveSpring is Non-Invasive

What does that mean?What does that mean? You are not forced to import or extend any You are not forced to import or extend any

Spring APIsSpring APIs An invasive API takes over your code.An invasive API takes over your code. Anti-patterns:Anti-patterns:

EJB forces you to use JNDIEJB forces you to use JNDI Struts forces you to extend Struts forces you to extend ActionAction

Page 11: Spring Framework

Spring CoreSpring CoreAt it’s core, Spring provides:At it’s core, Spring provides:

An Inversion of Control ContainerAn Inversion of Control Container Also known as Dependency Injection Also known as Dependency Injection • Setter Injection (Injection via Java Bean Setters)Setter Injection (Injection via Java Bean Setters)• Constructor Injection (Injection via Constructor arguments)Constructor Injection (Injection via Constructor arguments)An AOP FrameworkAn AOP Framework Spring provides a proxy-based AOP frameworkSpring provides a proxy-based AOP framework You can alternatively integrate with AspectJ or You can alternatively integrate with AspectJ or

AspectWerkzAspectWerkz A Service Abstraction LayerA Service Abstraction Layer

Consistent integration with various standard and 3Consistent integration with various standard and 3rdrd party party APIsAPIs

These together enable you to write powerful, These together enable you to write powerful, scalable applications using POJOs.scalable applications using POJOs.

Page 12: Spring Framework

Spring Core (Continue)Spring Core (Continue)

Spring at it’s core, is a Spring at it’s core, is a framework for wiring up your framework for wiring up your entire applicationentire application

BeanFactories BeanFactories are the heart of are the heart of SpringSpring

Page 13: Spring Framework

BeanFactoriesBeanFactories

A A BeanFactoryBeanFactory is typically configured in is typically configured in an XML file with the root element: an XML file with the root element: <beans><beans>

The XML contains one or more <bean> The XML contains one or more <bean> elementselements id (or name) attribute to identify the beanid (or name) attribute to identify the bean class attribute to specify the fully qualified class attribute to specify the fully qualified

classclass

Page 14: Spring Framework

BeanFactoriesBeanFactories

By default, beans are treated as By default, beans are treated as singletonssingletons

Can also be prototypesCan also be prototypes

Here is an example:Here is an example:<beans> <bean id=“widgetService” class=“com.zabada.base.WidgetService”> <property name=“poolSize”> <!—-property value here--> </property> </bean></beans>

The bean’s IDThe bean’s fully-qualified classname

Maps to a setPoolSize() call

Page 15: Spring Framework

Property Values for Property Values for BeanFactoriesBeanFactories

Strings and NumbersStrings and Numbers

Arrays and CollectionsArrays and Collections

<property name=“size”><value>42</value></property>

<property name=“name”><value>Jim</value></property>

<property name=“hobbies”> <list> <value>Basket Weaving</value> <value>Break Dancing</value> </list></property>

Page 16: Spring Framework

Property Values for Property Values for BeanFactories (continued)BeanFactories (continued)

The real magic comes in when you can setThe real magic comes in when you can set

a property on a bean that refers to anothera property on a bean that refers to another

bean in the configuration:bean in the configuration:

This is the basic conceptThis is the basic concept

of Inversion of Controlof Inversion of Control

<bean name=“widgetService” class=“com.zabada.base.WidgetServiceImpl”> <property name=“widgetDAO”> <ref bean=“myWidgetDAO”/> </property></bean> calls

setWidgetDAO(myWidgetDAO)where myWidgetDAO is another bean defined in the configuration

Page 17: Spring Framework

Dependency InjectionDependency Injection(Inversion of Control)(Inversion of Control)

Complicated sounding terms for a Complicated sounding terms for a fairly simple conceptfairly simple concept

The “Hollywood Principle”: Don’t call The “Hollywood Principle”: Don’t call me, I’ll call youme, I’ll call you

Dependencies used from within a Dependencies used from within a bean aren’t asked for outwardly, but bean aren’t asked for outwardly, but are injected into the bean by the are injected into the bean by the containercontainer

Page 18: Spring Framework

Dependency InjectionDependency Injection(Inversion of Control)(Inversion of Control)

Eliminates lookup code from within Eliminates lookup code from within your applicationyour application

Allows for pluggablity and hot Allows for pluggablity and hot swappingswapping

Promotes good OO designPromotes good OO design Enables reuse of existing codeEnables reuse of existing code Makes your application extremely Makes your application extremely

testabletestable

Page 19: Spring Framework

A Very Special BeanFactory:A Very Special BeanFactory:the ApplicationContextthe ApplicationContext

An An ApplicationContextApplicationContext is a is a BeanFactoryBeanFactory, but adds “framework” , but adds “framework” features such as:features such as: i18n messagesi18n messages Event notificationsEvent notifications

This is what you will probably most This is what you will probably most often use in your Spring applicationsoften use in your Spring applications

Page 20: Spring Framework

AOP (Aspect-Oriented AOP (Aspect-Oriented Programming)Programming)

AOP decomposes a system into concerns, instead AOP decomposes a system into concerns, instead of objects.of objects.

Deals with "aspects" that Deals with "aspects" that cross-cutcross-cut across the across the code and can be difficult or impossible to code and can be difficult or impossible to modularize with OOPmodularize with OOP

The most common example given is loggingThe most common example given is logging Code for doing logging typically must be scattered all Code for doing logging typically must be scattered all

over a systemover a system With AOP, you can declare, for example, that a system With AOP, you can declare, for example, that a system

should write a log record at the beginning and end of all should write a log record at the beginning and end of all method invocations.method invocations.

Page 21: Spring Framework

AOP (Aspect-Oriented AOP (Aspect-Oriented Programming)Programming)

AOP enables the delivery of services to POJOsAOP enables the delivery of services to POJOs Spring provides pre-packaged AOP services:Spring provides pre-packaged AOP services:

Declarative Transaction ManagementDeclarative Transaction Management SecuritySecurity LoggingLogging

You can write custom AOP services for:You can write custom AOP services for: AuditingAuditing CachingCaching Custom securityCustom security

Page 22: Spring Framework

Service Abstraction LayersService Abstraction Layers

Spring provides abstraction for:Spring provides abstraction for: Transaction ManagementTransaction Management

JTA, JDBC, othersJTA, JDBC, others Data AccessData Access

JDBC, Hibernate, JDO, TopLink, iBatisJDBC, Hibernate, JDO, TopLink, iBatis EmailEmail RemotingRemoting

EJB, Web Services, RMI, Hessian/BurlapEJB, Web Services, RMI, Hessian/Burlap

Page 23: Spring Framework

Service Abstraction LayersService Abstraction Layers

Benefits:Benefits: No implicit contracts with JNDI, etc.No implicit contracts with JNDI, etc. Insulates you from the underlying APIsInsulates you from the underlying APIs Greater reusabilityGreater reusability Spring abstractions always consist of Spring abstractions always consist of

interfacesinterfaces This makes testing simplerThis makes testing simpler For data access, Spring uses a generic For data access, Spring uses a generic

transaction infrastructure and DAO transaction infrastructure and DAO exception hierarchy that is common across exception hierarchy that is common across all supported platformsall supported platforms

Page 24: Spring Framework

Spring on the Web TierSpring on the Web Tier

Spring integrates nicely with Struts, Spring integrates nicely with Struts, WebWork, JSF, Tapestry, Velocity and WebWork, JSF, Tapestry, Velocity and other web frameworksother web frameworks

Spring also provides it’s own web Spring also provides it’s own web framework, Spring Web MVCframework, Spring Web MVC

Page 25: Spring Framework

Spring on the Web Tier – Spring on the Web Tier – Spring MVCSpring MVC

MVC web application framework built MVC web application framework built on core Spring functionalityon core Spring functionality

MVC dispatcher frameworkMVC dispatcher framework is highly configurable via strategy is highly configurable via strategy

interfaces and accommodates interfaces and accommodates multiple view technologies Likemultiple view technologies Like

JSP, Tiles, Velocity, FreeMarker, iTextJSP, Tiles, Velocity, FreeMarker, iText MVC comes in a Servlet edition MVC comes in a Servlet edition

working with the underlying working with the underlying environmentenvironment

Page 26: Spring Framework

Spring on the Web Tier – Spring on the Web Tier – Spring MVC (Cont)Spring MVC (Cont)

The Spring MVC Framework offers a The Spring MVC Framework offers a simple interface based infrastructure simple interface based infrastructure for handing web MVC architecturesfor handing web MVC architectures

Spring MVC components are treated Spring MVC components are treated as first-class Spring beansas first-class Spring beans Other Spring beans can easily be Other Spring beans can easily be

injected into Spring MVC componentsinjected into Spring MVC components Spring MVC components are easy to testSpring MVC components are easy to test

Page 27: Spring Framework

Spring MVC – Key InterfacesSpring MVC – Key Interfaces

Controller Controller ((org.springframework.web.servlet.mvc.Controllerorg.springframework.web.servlet.mvc.Controller)) Must implement Must implement ModelAndView handleRequest(request,response)ModelAndView handleRequest(request,response) This is the base controller interface, comparable to the notion This is the base controller interface, comparable to the notion

of a Struts Action.of a Struts Action. View View ((org.springframework.web.servlet.mvc.Vieworg.springframework.web.servlet.mvc.View))

Must implement Must implement void render( model, request, response)void render( model, request, response) This is the MVC view for a web interaction. Implementations This is the MVC view for a web interaction. Implementations

are responsible for rendering content, and exposing the model.are responsible for rendering content, and exposing the model. ModelModel

To complete the MVC trio, note that the model is typically To complete the MVC trio, note that the model is typically handled as a handled as a java.util.Mapjava.util.Map which is returned with the view which is returned with the view

the values of the model are available, for example in a JSP, the values of the model are available, for example in a JSP, using a using a <jsp:useBean/><jsp:useBean/> where the where the idid corresponds to the key corresponds to the key value in the Mapvalue in the Map

Page 28: Spring Framework

Spring on the Web Tier: Spring on the Web Tier: Integration with Other Integration with Other

FrameworksFrameworks Spring integrates nicely with other web Spring integrates nicely with other web

frameworks with two methodologies:frameworks with two methodologies: Look up Spring beans within Controllers/Actions via the Look up Spring beans within Controllers/Actions via the

convenience static method:convenience static method: WebApplicationContextUtils.getWebApplicationContext( servletContext)WebApplicationContextUtils.getWebApplicationContext( servletContext).getBean(“beanName”).getBean(“beanName”)

Configure the Controllers/Actions for the web framework Configure the Controllers/Actions for the web framework in a Spring BeanFactory and then use Spring provided in a Spring BeanFactory and then use Spring provided proxies in the actual web framework configurationproxies in the actual web framework configuration

When available, this methodology is preferredWhen available, this methodology is preferred This approach lets you design your Controllers/Actions with This approach lets you design your Controllers/Actions with

dependency injection and makes your Controller/Actions dependency injection and makes your Controller/Actions more testablemore testable

Page 29: Spring Framework

Spring ORMSpring ORM

ORM Module in Spring Relates With ORM Module in Spring Relates With the Database accessthe Database access

Provides Integration Layer for PopularProvides Integration Layer for Popular

Object Relating Mapping API’s Object Relating Mapping API’s includingincluding

JDO , Hibernate etcJDO , Hibernate etc

Page 30: Spring Framework

Spring DAOSpring DAO

Spring DAO (Data access object) Spring DAO (Data access object) module module

supports for standardizing data access supports for standardizing data access

work using Technologies like work using Technologies like

JDBCJDBC

HibernateHibernate

JDO, etcJDO, etc