spring basics

61
Spring 2.5 Framework Dhaval P. Shah 1

Upload: dhaval-shah

Post on 11-May-2015

973 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Spring Basics

Spring 2.5 Framework

Dhaval P. Shah

1

Page 2: Spring Basics

My Introduction

6.5+ years of experience in developing/supporting enterprise applications

SCJP 1.4

SCWCD 1.4

2

Page 3: Spring Basics

Agenda

Spring Jump start

Core Spring

Spring AOP

Spring JDBC

Spring Transaction

3

Page 4: Spring Basics

Pre-requisites

Core Java

JDBC

JNDI

Basic usage of IDE

4

Page 5: Spring Basics

What this training is not -

An expert in Spring

Having detailed discussion on all the topics of Spring

5

Page 6: Spring Basics

Spring jump start

Why Spring?

Spring overview Lightweight

IOC

Aspect Oriented

Container

Framework

6

Page 7: Spring Basics

Spring jump start [Contd.]

Spring Modules

Spring overview Lightweight

IOC

Aspect Oriented

Container

Framework

7

Page 8: Spring Basics

SPRING - Core

8

Page 9: Spring Basics

DI / IoC

Brief history about DI Dependency Inversion: Precursor to Dependency Injection

What is DI?

DI Vs IOC

Types of IOC Dependency Pull

Contextualized Dependency Lookup (CDL)

Types of DI Constructor

Setter

9

Page 10: Spring Basics

Types of IOC

10

Page 11: Spring Basics

Types of IOC [Contd.]

2. Contextualized Dependency Lookup

public class ContextualizedDependencyLookup implements ManagedComponent {

private Dependency dep;

public void performLookup(Container container) {

this.dep = (Dependency)container.get Dependency("myDependency");

}

}

11

Page 12: Spring Basics

Types of DI

1. Constructor Dependency

public class ConstructorInjection {

private Dependency dep;

public ConstructorInjection(Dependency dep) {

this.dep = dep;

}

}

12

Page 13: Spring Basics

Types of IOC [Contd.]

2. Setter Dependency

public class SetterInjection {

private Dependency dep;

public void setMyDependency(Dependency dep) { this.dep = dep;

}

}

13

Page 14: Spring Basics

Injection Vs Lookup

Disadvantages of Lookup Need to obtain handler of Registry to interact

Classes are dependent on classes & interfaces of IOC container

Testing in isolation from container becomes difficult

Advantages of Injection Minimal impact on existing code

Classes are completely decoupled from IOC container

Testing becomes much more easier

14

Page 15: Spring Basics

Setter Injection Vs Constructor Injection

15

Page 16: Spring Basics

Dependency Injection with Spring

Hello World example - [HelloWorldMainApp]

Beans & Bean Factories –

Setter DI example – [SetterDependencyInjectionMainApp]

Constructor DI example – [Main] Constructor confusion example – [ConstructorConfusionDemo]

16

Page 17: Spring Basics

Injecting Beans

17

Page 18: Spring Basics

Injecting bean using Bean Alias

18

Page 19: Spring Basics

Bean Factory Nesting

BeanFactory parent = new XmlBeanFactory(new FileSystemResource("./com/src/conf/parent.xml"));

BeanFactory child = new XmlBeanFactory(new FileSystemResource(

"./com/src/conf/beans.xml"), parent);

19

Page 20: Spring Basics

Understanding Bean Naming

20

Page 21: Spring Basics

Bean Instantiation Modes

Singleton

Non-Singleton

21

Page 22: Spring Basics

Bean Instantiation Modes [Contd.]

Non-Singleton Instantiation ModesMode Description

Prototype Every call to the getBean() method returns a new instance of the bean.

request Every call to the getBean() method in a web application will return a unique instance of the bean for every HTTP request. This behavior is only implemented in the WebApplicationContext and its subinterfaces.

session Calls to the getBean() method will return a unique instance of the bean for every HTTP Session. Just like request, this scope is only available in WebApplicationContext and its subinterfaces.

global session

The getBean() calls will return a unique instance of the bean for the global HTTP session in a portlet context. Just like request and session scopes, this instantiation mode is only supported in WebApplicationContext and its subinterfaces. 22

Page 23: Spring Basics

Bean Instantiation Modes [Contd.]

Choosing an instantiation mode Singleton

Shared objects with no state Shared objects with read only state Shared objects with shared state High throughput objects with writable state

Non-Singleton Objects with writable state Objects with private state

Bean scope example – [ScopeDemo]

23

Page 24: Spring Basics

Resolving Dependencies

<bean id="A" class="com.apress.prospring.ch4.BeanA" depends-on=“B"/>

<bean id="B" class="com.apress.prospring.ch4.BeanB"/>

24

Page 25: Spring Basics

Auto wiring your Beans

Spring supports 4 modes of auto wiring byName byType Constructor Autodetect

Auto wiring example – [AutowiringDemo]

When to use

25

Page 26: Spring Basics

Checking Dependencies

Spring has 3 modes for dependency checking simple

object

all

Example

<bean id="simpleBean1" class="com.innotech.spring.training.SimpleBean“ dependency-check="simple">

26

Page 27: Spring Basics

Bean Inheritance

27

Page 28: Spring Basics

Life Cycle of Spring Bean

28

Page 29: Spring Basics

Life Cycle of Spring Bean [Contd.]

BeanFactoryPostProcessor Executes after spring has finished constructing BeanFactory but

before BeanFactory constructs beans

BeanFactoryPost-Processors of SpringPost-Processors

Description

AspectJWeavingEnabler

This post-processor registers AspectJ’s ClassPreProcessorAgentAdapter to be used in Spring’s LoadTimeWeaver

CustomAutowireConfigurer

This one allows you to specify annotations, in addition to @Qualifier, to indicate that a bean is a candidate for automatic wiring.

CustomEditorConfigurer

This registers the PropertyEditor implementations that Spring will use in attempts to convert string values in the configuration files to types required by the beans.

29

Page 30: Spring Basics

Life Cycle of Spring Bean [Contd.]

BeanFactoryPost-Processors of Spring

Post-Processors

Description

CustomScopeConfigurer

Use this post-processor to configure custom scopes (in addition to singleton, prototype, request, session, and globalSession) in the configuration file. Set the scopes property to a Map containing the scope name as key and the implementation of the Scope interface as value.

PreferencesPlaceholderConfigurer

This post-processor will replace the values in beans' properties using JDK 1.4’s Preferences API. The Preferences API states that it will try to resolve a value first from user preferences (Preferences.userRoot()), then system preferences (Preferences.systemRoot()), and finally from a preferences file.

PropertyPlaceholderConfigurer

This post-processor will replace values of properties with values loaded from the configured properties file, if the values follow certain formatting rules (by default, ${property-name}). 30

Page 31: Spring Basics

Life Cycle of Spring Bean [Contd.]

BeanFactoryPost-Processors of Spring

Post-Processors

Description

PropertyOverrideConfigurer

This post-processor will replace values of beans’ properties from values loaded from the specified properties file. It will search the properties file for a property constructed from the bean name and property: for property a of bean x, it will look for x.a in the properties file. If the property does not exist, the post-processor will leave the value found in the configuration file.

ServletContextPropertyPlaceholderConfigurer

This post-processor extends PropertyPlaceholderConfigurer; therefore, it replaces beans’ properties if they follow the specified naming convention. In addition to its superclass, this processor will load values from context-param entries of the servlet that is hosting the application.

31

Page 32: Spring Basics

Life Cycle of Spring Bean [Contd.]

BeanPostProcessor of Spring has 2 methods postProcessBeforeInitialization

postProcessAfterInitialization

Spring Life Cycle example – [LifeCycleDemo, SimpleBeanDemo]

32

Page 33: Spring Basics

Spring’s ApplicationContext

Its an interface same as BeanFactory

ApplicationContext Vs BeanFactory

Implementation of ApplicationContext ClassPathXmlApplicationContext FileSystemXmlApplicationContext XmlWebApplicationContext

33

Page 34: Spring Basics

Spring’s built-in Property Editors

Property Editor Reg. by Default

Description

ByteArrayPropertyEditor

Y This PropertyEditor converts a String value into an array of bytes.

ClassEditor Y The ClassEditor converts from a fully qualified class name into a Class instance. When using this PropertyEditor, be careful not to include any extraneous spaces on either side of the class name when using XmlBeanFactory, because this results in a ClassNotFoundException.

CustomBooleanEditor

N This customizable editor for Boolean values is intended to be used in UI-centric code, where it can parse different String representations of Boolean values; for example, “Yes”/ “No” or “Ano”/“Ne”.

34

Page 35: Spring Basics

Spring’s built-in Property Editors [Contd.]

Property Editor

Reg. by Default

Description

CustomCollectionEditor

N This PropertyEditor can be used to create any type of the Java Collections framework or an array.

CustomDateEditor

N Just like the CustomBooleanEditor, this PropertyEditor is typically used in the controller’s initBinder method to enable the application to parse dates entered in a localespecific format to a java.util.Date.

FileEditor Y The FileEditor converts a String file path into a File instance. Spring does not check to see if the file (or directory) exists.

CustomNumberEditor

N This PropertyEditor converts a String into an Integer, a Long, a BigDecimal, or any other Number subclass.

35

Page 36: Spring Basics

Spring’s built-in Property Editors [Contd.]

Property Editor

Reg. by Default

Description

LocaleEditor Y The LocaleEditor converts the String representation of a locale, such as en-GB, into a java.util.Locale instance.

PatternEditor Y This ResourceEditor converts a regular expression (passed in as a String) into a java.util.regex.Pattern instance.

StringTrimmerEditor

N The StringTrimmerEditor can be used to trim nonempty Strings and to transform each empty String into null.

InputStreamEditor

Y This editor will convert a String into an InputStream. Note that this PropertyEditor is a not reflective; it can only convert String to InputStream, not the other way around. Internally, the conversion is achieved by instantiating a temporary ResourceEditor for a Resource. 36

Page 37: Spring Basics

Spring’s built-in Property Editors [Contd.]

Property Editor

Reg. by Default

Description

PropertiesEditor

Y PropertiesEditor converts a String in the format key1=value1\n key2=value2\n keyn=valuen into an instance of java.util.Properties with the corresponding properties configured.

StringArrayPropertyEditor

Y The StringArrayPropertyEditor class converts a comma-separated list of String elements into a String array.

URLEditor N The URLEditor converts a String representation of a URL into an instance of java.net.URL.

37

Page 38: Spring Basics

SPRING AOP

38

Page 39: Spring Basics

Spring AOP

AOP background

39

Page 40: Spring Basics

Spring AOP [Contd.]

AOP Concepts Aspect Advice JoinPoint PointCut Target Introduction Proxy Weaving

Compile time Classload time Runtime

Types of AOP Static AOP Dynamic AOP

40

Page 41: Spring Basics

Types of Advice

Advice Name Interface

Before org.springframework.aop.MethodBeforeAdvice

After Returning org.springframework.aop.AfterReturningAdvice

Around org.aopalliance.intercept.MethodInterceptor

Throws org.springframework.aop.ThrowsAdvice

Introduction org.springframework.aop.IntroductionInterceptor

41

Page 42: Spring Basics

The Pointcut Interface

public interface Pointcut {

ClassFilter getClassFilter ();

MethodMatcher getMethodMatcher();

}

public interface ClassFilter{

boolean matches(Class clazz);

}

public interface MethodMatcher{

boolean matches(Method m, Class targetClass);

boolean isRuntime();

boolean matches(Method m, Class targetClass,

Object[] args);

} 42

Page 43: Spring Basics

Types of Pointcut

Implementation Class

Description

org.springframework.aop.support.ComposablePointcut

The ComposablePointcut class is used to compose two or more pointcuts together with operations such as union() and intersection().

org.springframework.aop.support.ControlFlowPointcut

The ControlFlowPointcut is a special case pointcut that matches all methods within the control flow of another method, that is, any method that is invoked either directly or indirectly as the result of another method being invoked.

org.springframework.aop.support.JdkRegexpMethodPointcut

The JdkRexepMethodPointcut allows you to define pointcuts using JDK 1.4 regular expression support. This class requires JDK 1.4 or higher.

org.springframework.aop.AnnotationMatchingPointcut

The AnnotationMatchingPointcut class is used for creating Java 5 annotated pointcuts.

43

Page 44: Spring Basics

Types of Pointcut [Contd.]

Implementation Class

Description

org.springframework.aop.support.NameMatchMethodPointcut

Using the NameMatchMethodPointcut, you can create a pointcut that performs simple matching against a list of method names.

org.springframework.aop.StaticMethodMatcherPointcut

The StaticMethodMatcherPointcut class is intended as a base for building static pointcuts.

org.springframework.aop.DynamicMethodMatcherPointcut

The DynamicMethodMatcherPointcut class is a convenient superclass for building dynamic pointcuts that are aware of method arguments at runtime.

org.springframework.aop.AspectJExpressionPointcut

The AspectJExpressionPointcut convenient class is used for defining pointcuts using AspectJ expression language. Note that only method execution pointcuts can be defined, as Spring AOP does not support other AspectJ pointcuts in the current version. 44

Page 45: Spring Basics

SPRING - JDBC

45

Page 46: Spring Basics

Concepts in Spring Data Access Support

Understanding Spring’s DataAccessException You are not forced to handle DataAccessException Spring classifies exception for you

46

Page 47: Spring Basics

Concepts in Spring Data Access Support [Contd.]

Exception Description

CleanupFailureDataAccessException

An operation completes successfully, but an exception occurs while cleaning up database resources (e.g., closing a Connection).

DataAccessResourceFailureException

A data access resource fails completely, such as notbeing able to connect to a database.

DataIntegrityViolationException

An insert or update results in an integrity violation,such as a violation of a unique constraint.

DataRetrievalFailureException

Certain data could not be retrieved, such as not finding a row by primary key.

DeadlockLoserDataAccessException

The current process was a deadlock loser.

IncorrectUpdateSemanticsData-AccessException

When something unintended happens on an update,such as updating more rows than expected. Whenthis exception is thrown, the operation’s transactionhas not been rolled back.

47

Page 48: Spring Basics

Concepts in Spring Data Access Support [Contd.]

Exception Description

InvalidDataAccessApiUsageException

A data access Java API is used incorrectly, such asfailing to compile a query that must be compiledbefore execution.

InvalidDataAccessResourceUsageException

A data access resource is used incorrectly, such asusing bad SQL grammar to access a relational database.

OptimisticLockingFailureException

There is an optimistic locking failure. This will bethrown by ORM tools or by custom DAO implementations.

TypeMismatchDataAccessException

There is a mismatch between Java type and datatype, such as trying to insert a String into anumeric database column.

UncategorizedDataAccessException

Something goes wrong, but a more specific exception cannot be determined.

48

Page 49: Spring Basics

JDBC Data Access Support

Using JDBCTemplate

49

Page 50: Spring Basics

JDBC Data Access Support [Contd.]

Operations of JDBCTemplate JdbcTemplate.execute JdbcTemplate.query JdbcTemplate.update JdbcTemplate.batchUpdate

50

Page 51: Spring Basics

JdbcDaoSupport

51

Page 52: Spring Basics

SPRING - TRANSACTION

52

Page 53: Spring Basics

Spring Transaction

What is TRANSACTION?

Types of Transaction Local Transaction Global Transaction

Properties of Transaction Atomicity Consistency Isolation Durability

53

Page 54: Spring Basics

TransactionDefinition interface

public interface TransactionDefinition {

int getPropagationBehavior();

int getIsolationLevel();

int getTimeout();

boolean isReadOnly();

}

54

Page 55: Spring Basics

Spring’s Transaction Isolation levels

Isolation Level Description

ISOLATION_DEFAULT

Use the default isolation level of the underlying data-store.

ISOLATION_READ_UNCOMMITTED

Allows you to read changes that have not yet been committed. May result in dirty reads, phantom reads, and non-repeatable reads.

ISOLATION_READ_COMMITTED

Allows reads from concurrent transactions that have been committed. Dirty reads are prevented, but phantom and non-repeatable reads may still occur.

ISOLATION_REPEATABLE_READ

Multiple reads of the same field will yield the same results, unless changed by the transaction itself. Dirty reads and non-repeatable reads are prevented by phantom reads may still occur.

ISOLATION_SERIALIZABLE

This fully ACID-compliant isolation level ensures that dirty reads, non-repeatable reads, and phantom reads are all prevented. This is the slowest of all isolation levels because it is typically accomplished by doing full table locks on the tables involved in the transaction.55

Page 56: Spring Basics

Spring’s Transaction Propagation Behavior

Propagation Behavior

What does it mean

PROPAGATION_REQUIRED

Spring will use an active transaction if it exists. If not, Spring will begin a new transaction.

PROPAGATION_SUPPORTS

Spring will use an active transaction; if there is no active transaction, Spring will not start a new one.

PROPAGATION_MANDATORY

Spring will use an active transaction; if there is no active transaction, Spring will throw an exception.

PROPAGATION_REQUIRES_NEW

Spring will always start a new transaction. If an active transaction already exists, it is suspended.

56

Page 57: Spring Basics

Spring’s Transaction Propagation Behavior [Contd.]

Propagation Behavior

What does it mean

PROPAGATION_NOT_SUPPORTED

Spring will not execute the code in an active transaction. The code always executes non-transactionally and suspends any existing transaction.

PROPAGATION_NEVER

This always executes nontransactionally even if an active transaction exists. It throws an exception if an active transaction exists.

PROPAGATION_NESTED

This runs in a nested transaction if an active Transaction exists. If there is no active transaction, the code runs as if TransactionDefinition.PROPAGATION_REQUIRED is set.

57

Page 58: Spring Basics

Left overs’ !

Spring - Hibernate Spring - Webservice Spring schedulers Spring email Spring MVC Spring – UnitTesting/TDD . . . . . . . . . List goes on & on . . . :D

58

Page 59: Spring Basics

Questions?

59

Page 60: Spring Basics

Resources/References

Spring – www.springframework.org

Inversion of Control - http://www.martinfowler.com/articles/injection.html

Spring in Action – Walls, Breidenbach

60

Page 61: Spring Basics

Personal Information

E-mail : [email protected]

: http://twitter.com/dhaval201279

: http://in.linkedin.com/in/dhavalshah201279

61