92
Enterprise Application Development Sadegh Aliakbary An Introduction to Spring Framework www.JavaCup.ir

Enterprise Application Development Sadegh Aliakbary An Introduction to Spring Framework www. JavaCup.ir

Embed Size (px)

Citation preview

Enterprise Application Development

Sadegh Aliakbary

An Introduction to Spring Framework

www.JavaCup.ir

Contents redistribution is allowed if JAVACUP is noted as the source

2

Copyright ©2014 JAVACUP.ir All rights reserved. Redistribution of JAVACUP contents is not

prohibited if JAVACUP is clearly noted as the source in the used case.

JAVACUP shall not be liable for any errors in the content, or for any actions taken in reliance thereon.

Please send your feedback to [email protected]

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

3

Outline Dependency Injection and IoC Aspect Oriented Programming Spring Framework Spring vs. EJB

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

4

Introduction to Spring Framework

JAVACUP.ir

An open source Java platform Initially written by Rod Johnson, first released

under the Apache 2.0 license in June 2003 Spring is lightweight: the basic version = 2MB The core features can be used in any Java

application But there are extensions for web applications on

top of Java EE platform Spring targets to make J2EE development easier to

use Promote good programming practice By enabling a POJO-based programming model

Contents redistribution is allowed if JAVACUP is noted as the source

5

About Spring

JAVACUP.ir

Provides to create high performing, easily testable and

reusable code. is organized in a modular fashion simplifies java development

Contents redistribution is allowed if JAVACUP is noted as the source

6

Spring Modules

JAVACUP.ir

Spring is modular Allowing you to choose which modules are

applicable to you Provides about 20 modules

Contents redistribution is allowed if JAVACUP is noted as the source

7 JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

8

Spring Modules (cont’d)

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

9

Two Key Components of Spring

JAVACUP.ir

Dependency Injection (DI) Aspect Oriented Programming (AOP)

Contents redistribution is allowed if JAVACUP is noted as the source

10

Dependency Injection (DI)

JAVACUP.ir

Inversion of Control (IoC) Object coupling is bound at run time The binding process is achieved through

dependency injection Some argue that a “service locator” also provides

IoC Dependency injection is a software design

pattern DI allows the removal of hard-coded

dependencies Makes it possible to change them at run-time E.g.

as a simple way to load plugins dynamically to choose stubs or mock objects in test

environments vs. real objects in production environments.

Contents redistribution is allowed if JAVACUP is noted as the source

11

Dependency Injection (cont’d)

JAVACUP.ir

application classes should be as independent as possible To increase the possibility to reuse these classes and to test them independently

Dependency: an association between two classes E.g., class A is dependent on class B

Injection: class B will get injected into class A by the IoC

Dependency injection in the way of passing parameters to the constructor or by post-construction using setter methods

Contents redistribution is allowed if JAVACUP is noted as the source

12

Aspect Oriented Programming (AOP)

JAVACUP.ir

cross-cutting concerns The functions that span multiple points of an application

cross-cutting concerns are conceptually separate from the application's business logic E.g., logging, declarative transactions, security, and

caching The key unit of modularity

in OOP: the class in AOP: the aspect.

DI helps you decouple application objects from each other

AOP helps you decouple cross-cutting concerns from the objects that they affect

Contents redistribution is allowed if JAVACUP is noted as the source

13

Spring vs. EJB

JAVACUP.ir

Spring is light-weight And portable Offers many features of EJBs But simpler and easier No need to application server Core features: non-web applications Spring integrates many existing frameworks

ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies

Contents redistribution is allowed if JAVACUP is noted as the source

14

Spring vs. EJB (cont’d)

JAVACUP.ir

Testing is simpler Testing in non-web contexts Injection of mock objects

Lightweight IoC containers a consistent transaction management

interface scale down to a local transaction

using a single database scale up to global transactions

using JTA

Contents redistribution is allowed if JAVACUP is noted as the source

15

What is Spring?

JAVACUP.ir

Spring is the most popular application development framework for enterprise Java

Contents redistribution is allowed if JAVACUP is noted as the source

16

Trends: Spring vs. EJB

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

17

Spring Setup

JAVACUP.ir

Spring is some jar files Download from:

http://www.springsource.org/spring-community-download

And dependencies to some others Apache Common Logging API

Download from: http://commons.apache.org/logging/ AspectJ

aspectjrt.jar aspectjweaver.jar aspectj.jar Aopalliance.jar

Contents redistribution is allowed if JAVACUP is noted as the source

18

Spring – Hello World

JAVACUP.ir

Create your java project Simple application Web application

Add required Jar libraries Create source files

Class of beans Create bean configuration file (XML) Retrieve beans

Contents redistribution is allowed if JAVACUP is noted as the source

19

Source: Bean Classes

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

20

Bean Configuration File

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

21

Retrieve Beans

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

22

Spring Container

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

23

Spring Configuration Metadata

JAVACUP.ir

XML based configuration file. Annotation-based configuration Java-based configuration

Contents redistribution is allowed if JAVACUP is noted as the source

24

Spring IoC Containers (cont’d)

JAVACUP.ir

Spring BeanFactory Container the simplest container providing basic support for

DI for the purposes of backward compatibility E.g.

XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource("Beans.xml"));

Spring ApplicationContext Container This container adds more enterprise-specific

functionality E.g.

ApplicationContext context = new FileSystemXmlApplicationContext ("C:/Beans.xml");

Contents redistribution is allowed if JAVACUP is noted as the source

25

Spring Bean Definition

JAVACUP.ir

class name (id) scope constructor-arg properties autowiring mode lazy-initialization mode initialization method

A callback, invoked just after all properties on the bean have been set

For the sake of post-processing the bean creation destruction method

A callback, invoked when the container is destroyed.

Contents redistribution is allowed if JAVACUP is noted as the source

26

Spring Bean Scopes

JAVACUP.ir

Common Scopes singleton prototype

container creates new bean instance of the object every time a request for that specific bean is made.

Web-aware applications request session global-session

Contents redistribution is allowed if JAVACUP is noted as the source

27

Hint

JAVACUP.ir

Think about it: Spring bean container is not a web framework How a servlet container may prepare web-

contexts (request, session and global-session) for beans?

Listeners

Contents redistribution is allowed if JAVACUP is noted as the source

28

Note

JAVACUP.ir

Singleton pattern: singleton per class-loader

Singleton in Spring: singleton per bean definition, per container

Contents redistribution is allowed if JAVACUP is noted as the source

29

Default initialization and destroy methods

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

30

Bean Example

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

31

Bean Definition Inheritance

JAVACUP.ir

Parent property for beans

Contents redistribution is allowed if JAVACUP is noted as the source

32

Bean Definition Inheritance (cont’d)

JAVACUP.ir

Abstract beans Bean Definition Template

Contents redistribution is allowed if JAVACUP is noted as the source

33

Note

JAVACUP.ir

Relation of parent and abstract to OOP concepts?

Inheritance in Spring is different from OOP inheritance Parent has a different meaning

Abstract in Spring is different from OOP abstract

Parent and abstract is defined for beans (objects) not for classes

Contents redistribution is allowed if JAVACUP is noted as the source

34

Dependency Injection

JAVACUP.ir

Every java based application has a few objects that work together

In a complex Java application, application classes should be as independent as possible

To increase the possibility to reuse these classes

and to test them independently Dependency Injection (or sometime called

wiring) helps in gluing these classes together and same time keeping them independent.

Contents redistribution is allowed if JAVACUP is noted as the source

35

Example of a Dependency:

JAVACUP.ir

What is wrong with this code? we have created a dependency between the

TextEditor and the SpellChecker concrete class

Contents redistribution is allowed if JAVACUP is noted as the source

36

Solution

JAVACUP.ir

inversion of control like this:

Contents redistribution is allowed if JAVACUP is noted as the source

37

Dependency Injection Types

JAVACUP.ir

Constructor-based dependency injection Setter-based dependency injection

Contents redistribution is allowed if JAVACUP is noted as the source

38

Constructor-based dependency injection

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

39

Constructor-based dependency injection (2)

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

40

Constructor-based dependency injection (3)

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

41

Constructor-based dependency injection (4)

JAVACUP.ir

Perhaps the best way

Contents redistribution is allowed if JAVACUP is noted as the source

42

Setter-based

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

43

XML Configuration using p-namespace

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

44

Injecting Collections (list)

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

45

Injecting Collections (set)

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

46

Injecting Collections (map)

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

47

Injecting Collections (properties)

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

48

Injecting references in Collections

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

49

Inner Beans

JAVACUP.ir

Defined within the scope of another bean a <bean/> element inside the <property/>

or <constructor-arg/> elements Similar to inner classes, but: It is all about the scope of beans, nothing

about OOP

Contents redistribution is allowed if JAVACUP is noted as the source

50

Injecting null and empty string values

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

51

Auto-wiring

JAVACUP.ir

We can autowire relationships between collaborating beans

Without using <constructor-arg> or <property> elements

Decreases the amount of XML configuration you write

Use the autowire attribute of the <bean/> element no byName byType constructor

Contents redistribution is allowed if JAVACUP is noted as the source

52

Auto-wiring : byName

JAVACUP.ir

Autowiring by property name. Spring looks at the properties of the beans on

which autowire attribute is set to byName Tries to match and wire its properties with the

beans defined by the same names If matches are not found, it will throw

exceptions

Contents redistribution is allowed if JAVACUP is noted as the source

53

Auto-wiring : byType

JAVACUP.ir

Autowiring by property datatype Spring looks at the properties of the beans on

which autowire attribute is set to byType Tries to match and wire a property if its type

matches with exactly one of the beans If more than one such beans exists, a fatal

exception is thrown

Contents redistribution is allowed if JAVACUP is noted as the source

54

Auto-wiring : constructor

JAVACUP.ir

Similar to byType but type applies to constructor arguments If there is not exactly one bean of the

constructor argument type in the container, a fatal error is raised

Contents redistribution is allowed if JAVACUP is noted as the source

55

Limitations with autowiring

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

56

Annotation Based Configuration

JAVACUP.ir

Since Spring 2.5 to configure the dependency injection using

annotations instead of using XML to describe a bean wiring move the bean configuration into the

component class itself by using annotations

Contents redistribution is allowed if JAVACUP is noted as the source

57

Annotation-based Configuration Examples

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

58

Spring Java Based Configuration

JAVACUP.ir

To write most of your Spring configuration without XML

But with few Java-based annotations @Configuration: the class can be used by

the Spring IoC container as a source of bean definitions Instead of writing xml files

@Bean: the annotated method will return an object that should be registered as a bean in the Spring application context Instead of writing <bean> tags

Contents redistribution is allowed if JAVACUP is noted as the source

59

Example

JAVACUP.ir

Above code will be equivalent to the following XML configuration:

Contents redistribution is allowed if JAVACUP is noted as the source

60

Creating the Context

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

61

Injecting Bean Dependencies

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

62

AOP with Spring Framework

JAVACUP.ir

Aspect oriented programming cross-cutting concerns

logging, auditing, declarative transactions, security, and caching

The key unit of modularity in OOP is the class in AOP the unit of modularity is the aspect Dependency Injection helps you decouple your

application objects from each other AOP helps you decouple cross-cutting concerns from the

objects that they affect AOP is like triggers Spring AOP module provides interceptors

for example, when a method is executed you can add extra functionality before or after the method

execution

Contents redistribution is allowed if JAVACUP is noted as the source

63

AOP Terminology

JAVACUP.ir

Aspect A module which has APIs providing cross-cutting

requirements E.g., a logging module

Join point the actual place in the application where an action will be

taken E.g., before deposit() method

Advice the actual action to be taken

Point-cut a set of one or more join-points where an advice should be

executed Expressed using expressions or patterns

Contents redistribution is allowed if JAVACUP is noted as the source

64

AOP Terminology (2)

JAVACUP.ir

Introduction to add new methods or attributes to existing classes

Target object The object being advised by one or more aspects will always be a proxied object Also referred to as the advised object

Weaving The process of linking aspects with other application

types or objects, to create an advised object This can be done at compile time, load time, or at

runtime.

Contents redistribution is allowed if JAVACUP is noted as the source

65

Types of Advice

JAVACUP.ir

before before the a method execution

after around

before and after after-returning

only if method completes successfully after-throwing

only if method exits by throwing an exception

Contents redistribution is allowed if JAVACUP is noted as the source

66

XML Schema Based AOP with Spring

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

67

AOP Needed jars:

JAVACUP.ir

aspectjrt.jar aspectjweaver.jar aspectj.jar aopalliance.jar

Contents redistribution is allowed if JAVACUP is noted as the source

68

Example: AOP in Spring

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

69

Annotation-based Aspects

JAVACUP.ir

enabled by including <aop:aspectj-autoproxy/> inside XML Schema-based configuration file

The actual body of the businessService() is irrelevant should be empty

Contents redistribution is allowed if JAVACUP is noted as the source

70

Spring JDBC Framework

JAVACUP.ir

Simplifies JDBC programming Takes care of all the low-level details

opening the connection prepare and execute the SQL statement process exceptions handle transactions finally close the connection

Contents redistribution is allowed if JAVACUP is noted as the source

71

DataSource

JAVACUP.ir

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/test" /><property name="username" value="root" /><property name="password" value="123" />

</bean>

Contents redistribution is allowed if JAVACUP is noted as the source

72

JDBCTemplate Class

JAVACUP.ir

executes SQL queries update statements stored procedure calls performs iteration over ResultSets and

extraction of returned parameter values

Instances of the JdbcTemplate class are threadsafe

single instance of a JdbcTemplate is sufficient safely inject this shared reference into

multiple DAOs

Contents redistribution is allowed if JAVACUP is noted as the source

73

JDBCTemplate Examples

JAVACUP.ir

String SQL = "select count(*) from Student"; int rowCount = jdbcTemplateObject.queryForInt( SQL );

String SQL = "select age from Student where id = ?"; int age = jdbcTemplateObject.queryForInt(SQL,

new Object[]{10});

String SQL = "select name from Student where id = ?"; String name = jdbcTemplateObject.queryForObject(

SQL, new Object[]{10}, String.class);

Contents redistribution is allowed if JAVACUP is noted as the source

74

JDBCTemplate Examples (cont’d)

JAVACUP.ir

String SQL = "select * from Student where id = ?";Student student = jdbcTemplateObject.queryForObject(SQL, new Object[]{10}, new StudentMapper());

Contents redistribution is allowed if JAVACUP is noted as the source

75

Data Access Object (DAO)

JAVACUP.ir

DAOs provide a means to read/write data to the database

Contents redistribution is allowed if JAVACUP is noted as the source

76

Student DAO (Cont’d)

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

77

Spring Transaction Management

JAVACUP.ir

A database transaction is a sequence of actions that are treated as a single unit of work

four key properties described as ACID Atomicity Consistency Isolation Durability

Local vs. Global Transactions Programmatic vs. Declarative Declarative: annotations or XML based configuration

Declarative transaction management is preferable Spring supports declarative transaction management

through AOP

Contents redistribution is allowed if JAVACUP is noted as the source

78

Programmatic Transaction Management

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

79 JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

80

Declarative Transaction Management

JAVACUP.ir

Use Advices which creates a transaction-handling advice <tx:advice /> tag

Define a pointcut that matches all methods we wish to make transactional

Reference the transactional advice If a method name has been included in the

transactional configuration then created advice will begin the transaction before calling the method

Target method will be executed in a try / catch block. If the method finishes normally, the AOP advice

commits the transaction successfully otherwise it performs a rollback

Contents redistribution is allowed if JAVACUP is noted as the source

81

Spring’s Declarative Transaction Management

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

82

Bean Configuration for Transactions

JAVACUP.ir

Contents redistribution is allowed if JAVACUP is noted as the source

83

Using @Transactional

JAVACUP.ir

<!-- enable the configuration of transactional behavior based on annotations -->

<tx:annotation-driven transaction-manager="txManager"/>

<!-- a PlatformTransactionManager is still required -->

<bean id="txManager" class="org.springframework.jdbc.datasource. DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"/></bean>

You can use @Transactional for methods or Classes

Contents redistribution is allowed if JAVACUP is noted as the source

84

Spring Framework Alternatives

JAVACUP.ir

Google Guice provides support for dependency injection using

annotations Java EE 6 new standards

Contexts and Dependency Injection (CDI) specified by JSR 299 JBoss Weld is its reference implementation

CDI: a JCP specification included in Java EE 6 (JSR 299) Weld: the reference implementation of CDI Seam 3: a set of modules which extend CDI to

provide functionality beyond that offered by Java EE 6 Red HatJBossSeam Framwork Weld

Contents redistribution is allowed if JAVACUP is noted as the source

85

Decision point

JAVACUP.ir

Standards or (non-standard) frameworks? The benefits of standard technologies

Standards JSP, JSF, JPA, …

Non-standard technologies Spring, GWT, …

Contents redistribution is allowed if JAVACUP is noted as the source

86

JavaEE6’s Advocates Say:

JAVACUP.ir

The Age of Frameworks is Over The J2EE platform had its shortcoming

Spring quickly became the most prominent framework for easily building enterprise-ready applications

Helping developers avoid many of the pitfalls of the old enterprise Java platform

But J2EE represents the past, and Java EE 6 represents the future!

Java EE 6 promises us the ability to go beyond frameworks.

Contents redistribution is allowed if JAVACUP is noted as the source

87

JavaEE6’s Advocates Say: (cont’d)

JAVACUP.ir

Frameworks like Spring are really just a bridge between the mistakes of the J2EE past and the success of the Java EE 6 future.

Frameworks are out, and extensions to the Java EE 6 platform are in.

Now is the time to start looking past Spring, and looking forward to Seam and Weld and CDI technologies.

And to start shifting into a world of extensions, and moving away from frameworks,

Contents redistribution is allowed if JAVACUP is noted as the source

88

But, Spring’s Advocates Say:

JAVACUP.ir

In fact, Spring is more than a DI framework Perhaps, it is still the most popular application

development framework for enterprise Java Many extensions for easy integration with

other frameworks

Contents redistribution is allowed if JAVACUP is noted as the source

89

Review a Real Application

JAVACUP.ir

Beans for data access (DAO) E.g., Hibernate or JDBC classes

Beans for business logic Beans for presentation

E.g., GWT or JSF pages

How are the dependencies? How are the beans retrieved from bean container? How many beans:

Data-sources? DAOs? Logic classes? Presentation classes?

Contents redistribution is allowed if JAVACUP is noted as the source

90

Exercise

JAVACUP.ir

Write a web application “Add” and “List” forms for telephone contacts With all layers

Dao Business logic Presentation

Define the beans and spring-enable your project

Contents redistribution is allowed if JAVACUP is noted as the source

91

References and Material

JAVACUP.ir

Spring Framework Reference Documentation http://www.springsource.org/documentation

Spring Framework 3.1 Tutorial www.tutorialspoint.com/spring/spring_tutorial.pdf