159
Atul Kahate Spring Framework [email protected] www.atulkahate.com

Spring

Embed Size (px)

DESCRIPTION

Spring as taught by Atul Kahate Sir at SICSR

Citation preview

Page 1: Spring

Atul Kahate

Spring Framework

Atul Kahate

[email protected]

www.atulkahate.com

Page 2: Spring

What is Spring?� Open source framework created by Rod Johnson

� Created to ease the development of complex (enterprise) application development

� Makes the usage of plain JavaBeans possible where EJBs were used earlierused earlier

� POJO-based development

� Modular in nature

2 Spring | Atul Kahate

Fernandes Clara
framework
Fernandes Clara
POJO-
Fernandes Clara
Modular
Page 3: Spring

Spring Features� Lightweight – Small in size (2.5 MB JAR file), very little overheads in programming, Non-intrusive (no dependence on Spring-specific classes)

� Dependency Injection (DI) – Objects are passively provided with their dependencies, rather than they having to actively search for them (JNDI in the reverse)

� Aspect-Oriented Programming (AOP) – Separate business logic � Aspect-Oriented Programming (AOP) – Separate business logic from generic services, such as security, transaction management, etc

� Container –Takes care of lifecycle and configuration of applications

� Framework – Possible to configure complex applications from simple components with heavy usage of XML

3 Spring | Atul Kahate

Fernandes Clara
Lightweight
Fernandes Clara
Dependency
Fernandes Clara
Oriented
Fernandes Clara
Container
Fernandes Clara
Framework
Fernandes Clara
lifecycle
Fernandes Clara
applications
Fernandes Clara
heavy
Fernandes Clara
usage of XML
Fernandes Clara
� Container –Takes care of lifecycle and configuration of applications
Page 4: Spring

Spring Modules

4 Spring | Atul Kahate

Page 5: Spring

Core Container� Defines how beans are created, configured, and managed

� Contains the BeanFactory, which is the basis for the DI concept

5 Spring | Atul Kahate

Fernandes Clara
created,
Fernandes Clara
configured,
Fernandes Clara
managed
Fernandes Clara
BeanFactory,
Fernandes Clara
DI
Fernandes Clara
beans
Fernandes Clara
Container
Page 6: Spring

Application Context Module� Builds on the core container

� Makes spring a framework

� Extends the concept of BeanFactory, adding support for internationalization, application lifecycle events, and validationvalidation

� Supplies services such as email, JNDI access, EJB access, remoting, etc

6 Spring | Atul Kahate

Fernandes Clara
Builds
Fernandes Clara
container
Fernandes Clara
framework
Fernandes Clara
internationalization,
Fernandes Clara
BeanFactory,
Fernandes Clara
application
Fernandes Clara
lifecycle
Fernandes Clara
events,
Fernandes Clara
validation
Fernandes Clara
email,
Fernandes Clara
access,
Page 7: Spring

AOP Module� Serves as the basis for developing our own aspects for Spring applications

� Supports loose coupling of application objects

� Application-wide concerns such as transactions and security are decoupled from the objects to which they are appliedare decoupled from the objects to which they are applied

7 Spring | Atul Kahate

Fernandes Clara
Serves
Fernandes Clara
loose
Fernandes Clara
coupling
Fernandes Clara
application
Fernandes Clara
transactions
Fernandes Clara
security
Page 8: Spring

JDBC Abstraction and DAO Module� JDBC coding involves opening of connection, processing result sets, and closing connection

� This Spring module abstracts away this code to make our code simple

� Issues such as not closing database connections etc are taken � Issues such as not closing database connections etc are taken care of

� Provides a layer of abstraction to make database errors more meaningful

� Uses AOP module to provide transaction services

8 Spring | Atul Kahate

Fernandes Clara
connection,
Fernandes Clara
sets,
Fernandes Clara
closing
Fernandes Clara
errors
Fernandes Clara
module
Fernandes Clara
transaction
Fernandes Clara
not
Page 9: Spring

Object-Relational Mapping (ORM)

Integration Module

� Can be used as an alternative to JDBC

� Built over the DAO support for several ORM solutions, such as Hibernate, Java Persistence API, iBatis, Java Data Objects, etc

9 Spring | Atul Kahate

Fernandes Clara
Persistence
Fernandes Clara
ORM
Page 10: Spring

Java Management Extensions (JMX)

� Allows exposing our application’s beans as JMX beans

� Allows monitoring and reconfiguring a running application

10 Spring | Atul Kahate

Fernandes Clara
application’s
Fernandes Clara
beans
Fernandes Clara
JMX
Fernandes Clara
monitoring
Fernandes Clara
reconfiguring
Page 11: Spring

Java EE Connector API (JCA)� JCA provides a standard way of integrating Java applications with Mainframes, various databases, etc

� Spring provides a layer on top of JCA

11 Spring | Atul Kahate

Fernandes Clara
JCA)
Fernandes Clara
integrating
Fernandes Clara
Mainframes,
Fernandes Clara
databases,
Fernandes Clara
JCA
Fernandes Clara
layer
Fernandes Clara
top
Page 12: Spring

Spring MVC Framework� Spring can either integrate with an MVC framework such as Struts, JSF etc; and has its own MVC framework

12 Spring | Atul Kahate

Page 13: Spring

Spring Portlet MVC� Normal Web applications are request-response based

� Portlets are applications that aggregate information on to a single page, so that the request-response overhead is reduced

� Spring provides support for these kinds of applications

13 Spring | Atul Kahate

Fernandes Clara
request-
Fernandes Clara
response
Fernandes Clara
overhead
Fernandes Clara
aggregate
Fernandes Clara
information
Fernandes Clara
single
Page 14: Spring

NetBeans package beanname

Defining Beans in Spring

NetBeans package beanname

Spring | Atul Kahate14

Page 15: Spring

Usage of configuration files� In Spring, all beans need to be declared in a configuration file

� This avoids hard coding of class creation code in our applications

� This code is moved to a single location – the XML configuration file

Spring | Atul Kahate15

configuration file

� Implementations can be changed without any changes to our source code

� Note: The current example will not do anything useful!

Fernandes Clara
all beans
Fernandes Clara
configuration
Fernandes Clara
single location
Fernandes Clara
without
Fernandes Clara
changed
Page 16: Spring

beans3.xml<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

Spring | Atul Kahate16

<beans>

<bean id="string1" class="java.lang.String"/>

<bean name="string2" class="java.lang.String"/>

<bean class="java.lang.String"/>

</beans>

Page 17: Spring

BeanNaming.javapackage com.spring.beanname;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.FileSystemResource;

public class BeanNaming {

Spring | Atul Kahate17

public static void main(String[] args) {

BeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans3.xml"));

String s1 = (String)factory.getBean("string1");

String s2 = (String)factory.getBean("string2");

String s3 = (String)factory.getBean("java.lang.String");

}

}

Fernandes Clara
core.io.FileSystemResource;
Page 18: Spring

BeanFatcory� The core of Spring's design is the org.springframework.beanspackage, designed for use with JavaBean components.

� The next-highest layer of abstraction is the BeanFactory interface, an implementation of the Factory design pattern that enables objects to be created and retrieved by name. BeanFactory can also manage relationships between objects.

� BeanFactory supports two object modes.

Spring | Atul Kahate18

� BeanFactory supports two object modes.� Singleton mode provides a shared instance of the object with a particular name, which will be retrieved on lookup. Singleton is the default and most often used object mode. It is ideal for stateless service objects.

� Prototype mode ensures that each retrieval will result in the creation of an independent object. Prototype mode would be best used in a case where each user needed to have his or her own object.

Fernandes Clara
org.springframework.beans
Fernandes Clara
JavaBean
Fernandes Clara
BeanFactory
Fernandes Clara
interface,
Fernandes Clara
Factory
Fernandes Clara
design
Fernandes Clara
pattern
Fernandes Clara
created
Fernandes Clara
retrieved
Fernandes Clara
name.
Fernandes Clara
relationships
Fernandes Clara
modes.
Fernandes Clara
Singleton
Fernandes Clara
Prototype
Fernandes Clara
shared
Fernandes Clara
instance
Fernandes Clara
retrieved
Fernandes Clara
lookup.
Fernandes Clara
name,
Fernandes Clara
stateless
Fernandes Clara
retrieval
Fernandes Clara
each
Fernandes Clara
result
Fernandes Clara
creation
Fernandes Clara
each
Fernandes Clara
independent
Fernandes Clara
object.
Fernandes Clara
user
Fernandes Clara
own
Page 19: Spring

BeanFactory Interface� org.springframework.beans.factory.BeanFactory is a simple interface that can be

implemented for a range of underlying storage methods. The most commonly used BeanFactory definition is the XmlBeanFactory, which loads beans based on definitions in an XML file

BeanFactory factory = new XMLBeanFactory(new FileInputSteam("mybean.xml"));

� Beans defined in XML files are lazily loaded, which means that the beans themselves will

Spring | Atul Kahate19

� Beans defined in XML files are lazily loaded, which means that the beans themselves will not be instantiated until they are needed. To retrieve a bean from BeanFactory we can simply call the getBean() method passing in the name of the bean we want to retrieve:

MyBean mybean = (MyBean) factory.getBean("mybean");

� Each bean definition can be a POJO (defined by class name and JavaBean initialization properties) or a FactoryBean. The FactoryBean interface adds a level of indirection to the applications built using the Spring framework.

Fernandes Clara
underlying
Fernandes Clara
storage
Fernandes Clara
methods.
Fernandes Clara
getBean()
Fernandes Clara
retrieve
Fernandes Clara
POJO
Fernandes Clara
interface
Fernandes Clara
XmlBeanFactory,
Fernandes Clara
beans
Fernandes Clara
definitions
Fernandes Clara
XML
Fernandes Clara
level
Fernandes Clara
indirection
Page 20: Spring

D:\Atul\Lectures\SICSR\Web Technologies\WT-

Hello World in Spring

D:\Atul\Lectures\SICSR\Web Technologies\WT-2\spring\Spring-examples-sicsr

Page 21: Spring

Requirements� We need a service class

� This simply means the class that has our business logic

� To decouple the actual business logic from the caller, we can also have an interface that would be implemented by the service classservice class� The caller would program to the interface to create a loosely coupled logic

� We also need the tester class to test our service class

� Finally, we need an XML file for configuration

21 Spring | Atul Kahate

Fernandes Clara
service
Fernandes Clara
business
Fernandes Clara
business
Fernandes Clara
interface
Fernandes Clara
service
Fernandes Clara
interface
Fernandes Clara
coupled
Fernandes Clara
tester
Fernandes Clara
test
Fernandes Clara
service
Fernandes Clara
XML
Page 22: Spring

Hello World Depicted

Tester class (HelloApp.java)

Service interface (GreetingService.java)

Service class (GreetingServiceImpl.java)

Configuration(hello.xml)

22 Spring | Atul Kahate

Page 23: Spring

Hello World Depicted

Tester class (HelloApp.java)

public class HelloApp {

public static void main (String [] args) throws Exception {

BeanFactory factory = new XmlBeanFactory (new FileSystemResource ("hello.xml"));FileSystemResource ("hello.xml"));

GreetingService greetingService = (GreetingService) factory.getBean ("greetingService");

greetingService.sayGreeting();}

}

<?xml version="1.0”?>

<beans><bean id="greetingService"

class="com.spring.hello.GreetingServiceImpl">

<property name="greeting" value="Hello World!" />

</bean></beans>

Configuration (hello.xml)

23 Spring | Atul Kahate

Page 24: Spring

Understanding Tester Class – 1� BeanFactory factory = new XmlBeanFactory (new FileSystemResource ("hello.xml"));� Tester class uses the BeanFactory, which is the Spring container� Here, we are asking the Spring container to load a file named hello.xml into the container’s memory

� The hello.xml file contains this:� The hello.xml file contains this:<bean id="greetingService" class="com.spring.hello.GreetingServiceImpl">

<property name="greeting" value="Hello World!" />

</bean>

� Indicates that some time later we want to (1) instantiate an object of the GreetingServiceImpl class by the name greetingService, and (2) call its setGreeting method, passing the value Hello World

� See next slide

24 Spring | Atul Kahate

Fernandes Clara
Spring
Fernandes Clara
container
Fernandes Clara
container’s
Fernandes Clara
memory
Page 25: Spring

Understanding Tester Class – 2� Code

GreetingService greetingService = (GreetingService) factory.getBean("greetingService");

� XML file<bean id="greetingService" class="com.spring.hello.GreetingServiceImpl">

<property name="greeting" value="Hello World!" /><property name="greeting" value="Hello World!" /></bean>

� Now, these two are linked and our code obtains an instance of the GreetingServiceImpl class in the form of a greetingService object

� See next slide

25 Spring | Atul Kahate

Page 26: Spring

Understanding Tester Class – 3� The following are thus equivalent:

<bean id="greetingService" class="com.spring.hello.GreetingServiceImpl">

<property name="greeting" value="Hello World!" />

</bean>

� ANDGreetingServiceImpl greetingService = new GreetingServiceImpl ();

greetingService.setGreeting (“Hello World!”);

� First is Spring-way of coding, the second is the traditional method

26 Spring | Atul Kahate

Page 27: Spring

Understanding Tester Class – 3� greetingService.sayGreeting();

� We now call the sayGreeting method on the greetingService object

27 Spring | Atul Kahate

Page 28: Spring

Understanding Dependency Injection

(DI)� Look at our XML file definition once again:

<bean id="greetingService" class="com.spring.hello.GreetingServiceImpl"><property name="greeting" value="Hello World!" />

</bean>

� We are injecting/feeding our bean with the desired value for the greeting propertythe greeting property� Traditionally, our bean needs to figure this out itself, not any more

� This is called as Dependency Injection (DI)� DI was originally called as Inversion of Control (IOC)

� “Acquisition of dependencies” gets inverted� Hence, IOC was renamed to DI

28 Spring | Atul Kahate

Fernandes Clara
injecting/
Fernandes Clara
greeting
Fernandes Clara
desired
Fernandes Clara
Injection
Page 29: Spring

Why DI?� Objects are provided their dependencies at creation time by some external entity that coordinates each entity in the application

� Helps in making the application loosely coupled

� If an object knows about its dependencies by the interfaces of � If an object knows about its dependencies by the interfaces of the dependencies (not based on their implementation or on how they were created), then the dependency implementation can be changed without the depending object knowing about it

29 Spring | Atul Kahate

Fernandes Clara
provided
Fernandes Clara
Objects
Fernandes Clara
dependencies
Fernandes Clara
creation
Fernandes Clara
external
Fernandes Clara
coordinates
Fernandes Clara
entity
Fernandes Clara
application
Fernandes Clara
application
Fernandes Clara
loosely
Fernandes Clara
coupled
Fernandes Clara
object
Fernandes Clara
dependencies
Fernandes Clara
interfaces
Page 30: Spring

GreetingService.java� /*� * To change this template, choose Tools | Templates� * and open the template in the editor.� */

� package com.spring.hello;

� /**� *� * @author atulk� */� public interface GreetingService { � void sayGreeting ();� }

30 Spring | Atul Kahate

Page 31: Spring

GreetingServiceImpl.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.hello;

� /**

� *

� * @author atulk

� */

� public class GreetingServiceImpl implements GreetingService {

� private String greeting;

� public GreetingServiceImpl () {}

� public GreetingServiceImpl (String greeting) {

� this.greeting = greeting;

� }

� public void sayGreeting () {

� System.out.println (greeting);

� }

� public void setGreeting (String greeting) {

� this.greeting = greeting;

� }

� }

31 Spring | Atul Kahate

Page 32: Spring

hello.xml� <?xml version="1.0" encoding="UTF-8"?>

� <!--

� Document : hello.xml

� Created on : May 26, 2008, 2:09 PM

� Author : atulk

� Description:

� Purpose of the document follows.

� -->

� <beans xmlns="http://www.springframework.org/schema/beans"

� xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

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

� http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

� <bean id="greetingService" class="com.spring.hello.GreetingServiceImpl">

� <property name="greeting" value="Hello World!" />

� </bean>

� </beans>

32 Spring | Atul Kahate

Fernandes Clara
<beans xmlns="http://www.springframework.org/schema/beans" � xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" � xsi:schemaLocation="http://www.springframework.org/schema/beans � http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
Page 33: Spring

HelloApp.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.hello;

� import org.springframework.beans.factory.BeanFactory;

� import org.springframework.beans.factory.xml.XmlBeanFactory;

� import org.springframework.core.io.FileSystemResource;

� /**

*� *

� * @author atulk

� */

� public class HelloApp {

� public static void main (String [] args) throws Exception {

� BeanFactory factory = new XmlBeanFactory (new FileSystemResource ("hello.xml"));

� GreetingService greetingService = (GreetingService) factory.getBean ("greetingService");

� greetingService.sayGreeting();

� }

� }

33 Spring | Atul Kahate

Page 34: Spring

package com.spring.simpleinterestcalculator

Another Example – Simple Interest

Calculation

package com.spring.simpleinterestcalculator

Spring | Atul Kahate34

Page 35: Spring

SimpleInterestCalculatorBean.java� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.simpleinterestcalculator ;

� /**

� *

� * @author atulk

� */

� class SimpleInterestCalculatorBean {

� private float years;

� private float principle;

� private float rate;

� SimpleInterestCalculatorBean() {

� }

� public void setYears(float years) {

� this.years = years;

Spring | Atul Kahate35

� this.years = years;

� }

� public float getYears() {

� return years;

� }

� public void setPrinciple(float principle) {

� this.principle = principle;

� }

� public float getPrinciple() {

� return principle;

� }

� public void setRate(float rate) {

� this.rate = rate;

� }

� public float calculate() {

� return (float) ((principle * rate * years) / 100);

� }

� public float getInterest() {

� return calculate();

� }

Page 36: Spring

beans6.xml� <?xml version = "1.0" ?>

� <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

� <beans>

� <bean id="SimpleInterestBean" class="com.spring.simpleinterestcalculator.SimpleInterestCalculatorBean">

� <property name="principle">

Spring | Atul Kahate36

� <property name="principle">

� <value>10000.00</value>

� </property>

� <property name="years">

� <value>10.00</value>

� </property>

� <property name="rate">

� <value>9.50</value>

� </property>

� </bean>

� </beans>

Page 37: Spring

Client.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.simpleinterestcalculator;

� /**

� *

� * @author atulk

� */

� import java.io.*;

� import org.springframework.beans.factory.*;

� import org.springframework.beans.factory.xml.*;

� import org.springframework.core.io.*;

� public class Client {

Spring | Atul Kahate37

� public static void main(String args[]) throws Exception {

� try {

� System.out.println("Starting interest calculator ...");

� BeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans6.xml"));

� SimpleInterestCalculatorBean interest =

� (SimpleInterestCalculatorBean) factory.getBean("SimpleInterestBean");

� System.out.println(interest.getInterest());

� }

� catch(Exception e1) {

� System.out.println("" + e1);

� }

� }

� }

Page 38: Spring

NetBeans: Spring-IOC-Example

Example of Traditional Coding Versus

Spring-style of Coding

NetBeans: Spring-IOC-Example

Spring | Atul Kahate38

Page 39: Spring

Requirement� We want to create a list of bank accounts, and then simply display the details of all of them

Spring | Atul Kahate39

Page 40: Spring

Version 1 of the Code� Create an Account class, which will hold information about the various accounts, such as account number, accountholder’s name, opening balance, etc

� Another class AccountMaster would create as many accounts as we require in a hashmap

Spring | Atul Kahate40

we require in a hashmap

� The Tester class tests the functionality by displaying information about all accounts

Page 41: Spring

Version 1� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.one;

� /**

� *

� * @author atulk

� */

� public class Account {

� private String accountNumber;

� private String accountName;

� private int openingBalance;

� private int currentBalance;

� public Account(String accountNumber, String accountName, int openingBalance, int currentBalance) {

� this.accountNumber = accountNumber;

� this.accountName = accountName;

� this.openingBalance = openingBalance;

Spring | Atul Kahate41

� this.currentBalance = currentBalance;

� }

� public String toString () {

� return "Bank: " +

� " Account number -- " + accountNumber +

� " Account Name -- " + accountName +

� " Opening Balance -- " + openingBalance +

� " Current Balance -- " + currentBalance +

� ".\n";

� }

� public String getAccountName() {

� return accountName;

� }

� public void setAccountName(String accountName) {

� this.accountName = accountName;

� }

� public String getAccountNumber() {

� return accountNumber;

� }

� public void setAccountNumber(String accountNumber) {

� this.accountNumber = accountNumber;

� }

� public int getCurrentBalance() {

� return currentBalance;

� }

� public void setCurrentBalance(int currentBalance) {

� this.currentBalance = currentBalance;

� }

� public int getOpeningBalance() {

Page 42: Spring

Version 1� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.one;

� import java.util.HashMap;

� import java.util.Iterator;

� /**

� *

� * @author atulk

� */

� public class AccountMaster {

� private String bankName;

� HashMap accounts = new HashMap ();

� public AccountMaster(String bankName) {

� this.bankName = bankName;

� System.out.println ("Bank name set to: " + this.bankName);

Spring | Atul Kahate42

� accounts.put ("100", new Account("1000", "test account 1", 1000, 10000));

� accounts.put ("2000", new Account("2000", "test account 2", 2000, 20000));

� accounts.put ("3000", new Account("3000", "test account 3", 3000, 30000));

� accounts.put ("4000", new Account("4000", "test account 4", 4000, 40000));

� accounts.put ("5000", new Account("5000", "test account 5", 5000, 50000));

� accounts.put ("6000", new Account("6000", "test account 6", 6000, 60000));

� System.out.println ("Exiting the constructor of GetAccount ...");

� }

� public String toString () {

� return "This is for Bank: " + bankName;

� }

� public HashMap findAccounts () {

� return accounts;

� }

� public Account findAccount (String accountNumber) {

� Iterator iter = accounts.values().iterator();

� while (iter.hasNext()) {

� Account account = (Account) iter.next();

� if (accountNumber.equals(account.getAcco untNumber()))

� return account;

� }

� return null;

� }

� }

Page 43: Spring

Version 1� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.one;

� import java.util.Iterator;

� /**

� *

� * @author atulk

� */

� public class Tester {

� private AccountMaster findAccount;

Spring | Atul Kahate43

� public Tester () {

� System.out.println ("1");

� findAccount = new AccountMaster ("My Bank");

� System.out.println ("2");

� }

� public void printAllAccounts () {

� System.out.println (findAccount.toString());

� Iterator iter = findAccount.findAccounts().values().iterator();

� while (iter.hasNext()) {

� Account account = (Account) iter.next();

� System.out.println (account.toString());

� }

� }

� public static final void main (String args []) {

� Tester tester = new Tester ();

� System.out.println ("After Tester");

� tester.printAllAccounts();

� }

� }

Page 44: Spring

Version 2 of the Code� Account class – No change

� AccountMaster class – Is now an interface, instead of being a concrete class

� HashMapAccountMaster class – Implements AccountMasterinterface

Spring | Atul Kahate44

interface

� OldTester – New class, which takes on the functionality of the earlier Tester class

� Tester – Modified to work with OldTester and AccountMasterclasses

Page 45: Spring

Version 2� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.two;

� /**

� *

� * @author atulk

� */

� public class Account {

� private String accountNumber;

� private String accountName;

� private int openingBalance;

� private int currentBalance;

� public Account(String accountNumber, String accountName, int openingBalance, int currentBalance) {

� this.accountNumber = accountNumber;

� this.accountName = accountName;

� this.openingBalance = openingBalance;

Spring | Atul Kahate45

� this.currentBalance = currentBalance;

� }

� public String toString () {

� return "Bank: " +

� " Account number -- " + accountNumber +

� " Account Name -- " + accountName +

� " Opening Balance -- " + openingBalance +

� " Current Balance -- " + currentBalance +

� ".\n";

� }

� public String getAccountName() {

� return accountName;

� }

� public void setAccountName(String accountName) {

� this.accountName = accountName;

� }

� public String getAccountNumber() {

� return accountNumber;

� }

� public void setAccountNumber(String accountNumber) {

� this.accountNumber = accountNumber;

� }

� public int getCurrentBalance() {

� return currentBalance;

� }

� public void setCurrentBalance(int currentBalance) {

� this.currentBalance = currentBalance;

� }

� public int getOpeningBalance() {

Page 46: Spring

Version 2� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.two;

� import java.util.HashMap;

Spring | Atul Kahate46

� /**

� *

� * @author atulk

� */

� public interface AccountMaster {

� HashMap getAccounts ();

� public Account getAccount (String accountNumber);

� }

Page 47: Spring

Version 2� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.two;

� import java.util.HashMap;

� import java.util.Iterator;

� /**

� *

� * @author atulk

� */

� public class HashMapAccountMaster implements AccountMaster {

� private String bankName;

� HashMap accounts = new HashMap ();

� public HashMapAccountMaster(String bankName) {

� this.bankName = bankName;

Spring | Atul Kahate47

� System.out.println ("Bank name set to: " + this.bankName);

� accounts.put ("100", new Account("1000", "test account 1", 1000, 10000));

� accounts.put ("2000", new Account("2000", "test account 2", 2000, 20000));

� accounts.put ("3000", new Account("3000", "test account 3", 3000, 30000));

� accounts.put ("4000", new Account("4000", "test account 4", 4000, 40000));

� accounts.put ("5000", new Account("5000", "test account 5", 5000, 50000));

� accounts.put ("6000", new Account("6000", "test account 6", 6000, 60000));

� System.out.println ("Exiting the constructor of GetAccount ...");

� }

� public String toString () {

� return "This is for Bank: " + bankName;

� }

� public HashMap getAccounts () {

� return accounts;

� }

� public Account getAccount (String accountNumber) {

� Iterator iter = accounts.values().iterator();

� while (iter.hasNext()) {

� Account account = (Account) iter.next();

� if (accountNumber.equals(account.getAcco untNumber()))

� return account;

� }

� return null;

� }

� }

Page 48: Spring

Version 2� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.two;

� import java.util.Iterator;

� /**

� *

� * @author atulk

� */

� public class OldTester {

� private AccountMaster accountMaster;

Spring | Atul Kahate48

� public OldTester () {

� }

� public void setAccountMaster (AccountMaster accountMaster) {

� this.accountMaster = accountMaster;

� }

� public AccountMaster getAccountMaster () {

� return this.accountMaster;

� }

� public void printAllAccounts () {

� System.out.println (accountMaster.toString());

� Iterator iter = accountMaster.getAccounts().values().iterator();

� while (iter.hasNext()) {

� Account account = (Account) iter.next();

� System.out.println (account.toString());

� }

� }

� }

Page 49: Spring

Version 2� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.two;

� /**

� *

� * @author atulk

Spring | Atul Kahate49

� */

� public class Tester {

� public static final void main(String args[]) {

� OldTester oldTester = new OldTester();

� AccountMaster accountMaster = new HashMapAccountMaster("My Bank");

� oldTester.setAccountMaster(accountMaster);

� oldTester.printAllAccounts();

� }

� }

Page 50: Spring

Version 3 of the Code� Using Spring

� Account class – No change

� AccountMaster class – No change

� HashMapAccountMaster class – No change

� OldTester class – No change

Spring | Atul Kahate50

� OldTester class – No change

� Tester class – Makes use of BeanFactory now

Page 51: Spring

Version 3� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.three;

� /**

� *

� * @author atulk

� */

� public class Account {

� private String accountNumber;

� private String accountName;

� private int openingBalance;

� private int currentBalance;

� public Account(String accountNumber, String accountName, int openingBalance, int currentBalance) {

� this.accountNumber = accountNumber;

� this.accountName = accountName;

� this.openingBalance = openingBalance;

Spring | Atul Kahate51

� this.currentBalance = currentBalance;

� }

� public String toString () {

� return "Bank: " +

� " Account number -- " + accountNumber +

� " Account Name -- " + accountName +

� " Opening Balance -- " + openingBalance +

� " Current Balance -- " + currentBalance +

� ".\n";

� }

� public String getAccountName() {

� return accountName;

� }

� public void setAccountName(String accountName) {

� this.accountName = accountName;

� }

� public String getAccountNumber() {

� return accountNumber;

� }

� public void setAccountNumber(String accountNumber) {

� this.accountNumber = accountNumber;

� }

� public int getCurrentBalance() {

� return currentBalance;

� }

� public void setCurrentBalance(int currentBalance) {

� this.currentBalance = currentBalance;

� }

� public int getOpeningBalance() {

Page 52: Spring

Version 3� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.three;

� import java.util.HashMap;

Spring | Atul Kahate52

� /**

� *

� * @author atulk

� */

� public interface AccountMaster {

� HashMap getAccounts ();

� public Account getAccount (String accountNumber);

� }

Page 53: Spring

Version 3� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.three;

� import java.util.HashMap;

� import java.util.Iterator;

� /**

� *

� * @author atulk

� */

� public class HashMapAccountMaster implements AccountMaster {

� private String bankName;

� private HashMap accounts = new HashMap ();

� public HashMapAccountMaster (String bankName) {

� System.out.println ("inside ...");

Spring | Atul Kahate53

� populateAccounts ();

� }

� public String toString () {

� return "This is for Bank: " + bankName;

� }

� public HashMap getAccounts () {

� return accounts;

� }

� public Account getAccount (String accountNumber) {

� Iterator iter = accounts.values().iterator();

� while (iter.hasNext()) {

� Account account = (Account) iter.next();

� if (accountNumber.equals(account.getAcco untNumber()))

� return account;

� }

� return null;

� }

� public String getBankName () {

� return bankName;

� }

� public void setBankName (String bankName) {

� this.bankName = bankName;

� }

� public void populateAccounts () {

� System.out.println ("initializing hashmap");

� accounts.put ("1000", new Account("1000", "test account 1", 1000, 10000));

� accounts.put ("2000", new Account("2000", "test account 2", 2000, 20000));

� accounts.put ("3000", new Account("3000", "test account 3", 3000, 30000));

� accounts.put ("4000", new Account("4000", "test account 4", 4000, 40000));

Page 54: Spring

Version 3� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.three;

� import java.util.Iterator;

� /**

� *

� * @author atulk

*/

Spring | Atul Kahate54

� */

� public class OldTester {

� private AccountMaster accountMaster;

� public OldTester () {

� }

� public void setAccountMaster (AccountMaster accountMaster) {

� this.accountMaster = accountMaster;

� }

� public AccountMaster getAccountMaster () {

� return this.accountMaster;

� }

� public void printAllAccounts () {

� System.out.println (accountMaster.toString());

� Iterator iter = accountMaster.getAccounts().values().iterator();

� while (iter.hasNext()) {

� Account account = (Account) iter.next();

� System.out.println (account.toString());

Page 55: Spring

Version 3� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.example.version.three;

� import org.springframework.beans.factory.BeanFactory;

� import org.springframework.beans.factory.xml.XmlBeanFactory;

� import org.springframework.core.io.FileSystemResource;

� /**

� *

Spring | Atul Kahate55

� *

� * @author atulk

� */

� public class Tester {

� public static final void main(String args[]) {

� BeanFactory factory = new XmlBeanFactory (new FileSystemResource ("beans.xml"));

� OldTester oldTester = (OldTester) factory.getBean ("oldTester");

� oldTester.printAllAccounts();

� }

� }

Page 56: Spring

Version 3� // Beans.xml

� <?xml version="1.0" encoding="UTF-8"?>

� <!--

� Document : hello.xml

� Created on : May 26, 2008, 2:09 PM

� Author : atulk

� Description:

� Purpose of the document follows.

� -->

� <beans xmlns="http://www.springframework.org/schema/beans"

Spring | Atul Kahate56

� <beans xmlns="http://www.springframework.org/schema/beans"

� xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

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

� http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

� <bean id="accountMaster"

� class="com.example.version.three.HashMapAccountMaster">

� <constructor-arg><value>My Bank</value></constructor-arg>

� </bean>

� <bean id="oldTester"

� class="com.example.version.three.OldTester">

� <property name="accountMaster"><ref bean="accountMaster" /></property>

� </bean>

� </beans>

Page 57: Spring

Package com.spring.forex

Forex Rates Example

Package com.spring.forex

Spring | Atul Kahate57

Page 58: Spring

ForexData.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.forex;

� /**

� *

� * @author atulk

� */

� public class ForexData {

� private String fromCurrency;

� private String toCurrency;

� private float rate;

� public String getFromCurrency() {

� return fromCurrency;

� }

� public void setFromCurrency(String fromCurrency) {

Spring | Atul Kahate58

� this.fromCurrency = fromCurrency;

� }

� public float getRate() {

� return rate;

� }

� public void setRate(float rate) {

� this.rate = rate;

� }

� public String getToCurrency() {

� return toCurrency;

� }

� public void setToCurrency(String toCurrency) {

� this.toCurrency = toCurrency;

� }

� public double getExchangeRate () {

� if (fromCurrency.equals ("USD") && toCurrency.equals ("INR")) {

� return 39.50;

� }

� else if (fromCurrency.equals ("INR") && toCurrency.equals ("USD")) {

� return 1 / 39.50;

� }

� // default

� return -99.99;

� }

� }

Page 59: Spring

beans7.xml� <?xml version = "1.0" ?>

� <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

� <beans>� <bean id="ForexData" class="com.spring.forex.ForexData">

Spring | Atul Kahate59

� <property name="fromCurrency">� <value>USD</value>� </property>� <property name="toCurrency">� <value>INR</value>� </property>� </bean>� </beans>

Page 60: Spring

Client.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.forex;

� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� import java.io.*;

� import org.springframework.beans.factory.*;

� import org.springframework.beans.factory.xml.*;

� import org.springframework.core.io.*;

Spring | Atul Kahate60

� public class Client {

� public static void main(String args[]) throws Exception {

� try {

� System.out.println("Starting interest calculator ...");

� BeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans7.xml"));

� ForexData forexData =

� (ForexData) factory.getBean("ForexData");

� System.out.println("Exchange rate between " + forexData.getFromCurrency() +

� " and " + forexData.getToCurrency() + " is " + forexData.getExchangeRate());

� }

� catch(Exception e1) {

� System.out.println("" + e1);

� }

� }

� }

Page 61: Spring

NetBeans Spring-examples-sicsr

Department and Employee Example

NetBeans Spring-examples-sicsr

Package com.spring.deptandemp

Spring | Atul Kahate61

Page 62: Spring

Department.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.deptandemp;

� /**

� *

� * @author AtulK

� */

� public class Department {

� String deptID;

� String deptName;

� Employee employee;

� public String getDeptID() {

� return deptID;

� }

� public void setDeptID(String deptID) {

Spring | Atul Kahate62

� this.deptID = deptID;

� }

� public String getDeptName() {

� return deptName;

� }

� public void setDeptName(String deptName) {

� this.deptName = deptName;

� }

� public Employee getEmployee() {

� return employee;

� }

� public void setEmployee(Employee employee) {

� this.employee = employee;

� }

� public Department(String deptID, String deptName, Employee employee) {

� this.deptID = deptID;

� this.deptName = deptName;

� this.employee = employee;

� }

� public Department() {

� }

� }

Page 63: Spring

Employee.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.deptandemp;

� /**

� *

� * @author AtulK

� */

� public class Employee {

� private String empID;

� private String empName;

� private int salary;

� public String getEmpID() {

� return empID;

� }

Spring | Atul Kahate63

� }

� public void setEmpID(String empID) {

� this.empID = empID;

� }

� public String getEmpName() {

� return empName;

� }

� public void setEmpName(String empName) {

� this.empName = empName;

� }

� public int getSalary() {

� return salary;

� }

� public void setSalary(int salary) {

� this.salary = salary;

� }

� public Employee() {

� }

� }

Page 64: Spring

Tester.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.deptandemp;

� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� import java.io.*;

� import org.springframework.beans.factory.*;

� import org.springframework.beans.factory.xml.*;

� import org.springframework.core.io.*;

Spring | Atul Kahate64

� public class Tester {

� public static void main(String args[]) throws Exception {

� try {

� System.out.println("Starting department and employee application ...");

� BeanFactory factory = new XmlBeanFactory(new FileSystemResource("beans10.xml"));

� Department department =

� (Department) factory.getBean("departmentBean");

� System.out.println("Department " + department.getDeptName()+ " has employee " +

� department.employee.getEmpName());

� }

� catch(Exception e) {

� System.out.println("Exception occurred!!! " + e);

� }

� }

� }

Page 65: Spring

beans10.xml� <?xml version="1.0" encoding="UTF-8"?>

� <beans xmlns="http://www.springframework.org/schema/beans"

� xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

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

� http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

� <bean id="employeeBean"

� class="com.spring.deptandemp.Employee">

� <property name = "empID">

� <value>999</value>

� </property>

� <property name = "empName">

� <value>My Employee Name</value>

� </property>

Spring | Atul Kahate65

� <property name = "salary">

� <value>5000</value>

� </property>

� </bean>

� <bean id="departmentBean"

� class="com.spring.deptandemp.Department">

� <property name = "deptID">

� <value>100</value>

� </property>

� <property name = "deptName">

� <value>My Department</value>

� </property>

� <property name = "employee">

� <ref bean = "employeeBean"></ref>

� </property>

� </bean>

� </beans>

Page 66: Spring

Passing one object to another as a DI

DI in detail

Passing one object to another as a DI

NetBeans package com.spring.hello.di

Page 67: Spring

Real-life DI� In real-life DI, we pass the object of one class to another object of a different class as a DI

� This way, if A is passed to B, B does not need to worry about how A was created, etc

� A’s implementation can be changed freely from a simple bean � A’s implementation can be changed freely from a simple bean to an EJB to a Web service etc

� Again, this can be done by using simple configurations in an XML file

67 Spring | Atul Kahate

Fernandes Clara
object
Fernandes Clara
one
Fernandes Clara
another
Fernandes Clara
different
Fernandes Clara
class
Fernandes Clara
DI
Fernandes Clara
implementation
Fernandes Clara
changed
Fernandes Clara
freely
Fernandes Clara
simple
Fernandes Clara
simple
Fernandes Clara
configurations
Page 68: Spring

Understanding the example

Model class (provider)

View class (renderer)

injected into

<beans><bean id="provider" class="HelloWorldModel"><constructor-arg><value>This is a configurable message</value><value>This is a configurable message</value>

</constructor-arg></bean>

<bean id="renderer" class="StandardOutView"><property name="model"><ref local="provider"/>

</property></bean>

</beans>

68 Spring | Atul Kahate

Page 69: Spring

Our Model� Model.java (Interface)

public interface Model {public String getMessage();}

� HelloWorldModel.java (Implementation)

public class HelloWorldModel implements Model {String mess;String mess;

public HelloWorldModel(String m){mess = m;

}

public String getMessage() {return mess;

}}

69 Spring | Atul Kahate

Page 70: Spring

Our View� View.java (Interface)

public interface View {public void render();

public void setModel(Model m);public Model getModel();

}

� StandardOutView.java (Implementation)

public class StandardOutView implements View {private Model model = null;

public void render() {if (model == null) {throw new RuntimeException(

"You must set the property model of class:"+ StandardOutView.class.getName());

}System.out.println(model.getMessage());

}

public void setModel(Model m) {this.model = m;

}

public Model getModel() {return this.model;

}

}

70 Spring | Atul Kahate

Fernandes Clara
� StandardOutView.java (Implementation) public class StandardOutView implements View { private Model model = null; public void render() { if (model == null) { throw new RuntimeException( "You must set the property model of class:" + StandardOutView.class.getName()); }
Fernandes Clara
public void setModel(Model m); public Model getModel();
Page 71: Spring

Our XML configuration file� Beans.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans><bean id="provider" class="HelloWorldModel"><constructor-arg><constructor-arg><value>This is a configurable message</value>

</constructor-arg></bean>

<bean id="renderer" class="StandardOutView"><property name="model"><ref local="provider"/>

</property></bean>

</beans>

71 Spring | Atul Kahate

Page 72: Spring

Our Client Code� HelloWorldXmlWithDI.java

import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.FileSystemResource;

public class HelloWorldXmlWithDI {

public static void main(String[] args) throws Exception {public static void main(String[] args) throws Exception {BeanFactory factory = getBeanFactory();View mr = (View) factory.getBean("renderer");mr.render();

}

private static BeanFactory getBeanFactory() throws Exception {BeanFactory factory = new XmlBeanFactory(new FileSystemResource(

”beans.xml"));return factory;

}}

72 Spring | Atul Kahate

Page 73: Spring

NetBeans package com.spring.simpleinjectbydi

Injecting by DI Example

NetBeans package com.spring.simpleinjectbydi

Spring | Atul Kahate73

Page 74: Spring

ClientTester.java

public class ClientTester {

private String name;private int age;…

public static void main(String[] args) {BeanFactory factory = new XmlBeanFactory(new FileSystemResource(“beans2.xml"));ClientTester simple = (ClientTester)factory.getBean("clientTester");factory.getBean("injectRef");System.out.println(simple);

}// set methods for all attributes of this class

Spring | Atul Kahate74

// set methods for all attributes of this class}

beans2. xml

<bean id="clientTester" class="com.spring.simpleinjectbydi.ClientTester"><property name="name"><value>Kishore Kumar</value>

</property>…

</bean>

Page 75: Spring

ClientTester.java

public class ClientTester {

private String name;private int age;…

public static void main(String[] args) {BeanFactory factory = new XmlBeanFactory(new FileSystemResource(“beans2.xml"));ClientTester simple = (ClientTester)factory.getBean("clientTester");factory.getBean("injectRef");System.out.println(simple);

}// set methods for all attributes of this class

Spring | Atul Kahate75

// set methods for all attributes of this class}

beans2. xml

<bean id="injectRef" class="com.spring.simpleinjectbydi.InjectRef"><property name="info"><ref local="infobyid"/>

</property></bean>

Page 76: Spring

InjectRef.java

public class InjectRef {

private Info info;

public void setInfo (Info info) {this.info = info;System.out.println(info.getInfo());

}}

InfoImpl.java

Spring | Atul Kahate76

public class InfoImpl implements Info {

private Encyclopedia enc;

public void setEncyclopedia(Encyclopedia enc) {this.enc = enc;

}

public String getInfo () {return "Encyclopedia's are a waste of money - use the Internet";

}

}

Info.java

public interface Info {public String getInfo ();

}

Page 77: Spring

InfoImpl.java

public class InfoImpl implements Info {

private Encyclopedia enc;

public void setEncyclopedia(Encyclopedia enc) {this.enc = enc;

}

public String getInfo () {return "Encyclopedia's are a waste of money - use the Internet";

}

}

Spring | Atul Kahate77

}

public class Encyclopedia {

}

Page 78: Spring

Encylopedia.java� Deliberately kept empty

public class Encyclopedia {

}

Spring | Atul Kahate78

}

Page 79: Spring

Info.javapublic interface Info {

public String getInfo ();

}

Spring | Atul Kahate79

Page 80: Spring

InfoImpl.javapublic class InfoImpl implements Info {

private Encyclopedia enc;

public void setEncyclopedia(Encyclopedia enc) {this.enc = enc;

Spring | Atul Kahate80

this.enc = enc;}

public String getInfo () {return "Encyclopedia's are a waste of money - use the Internet";

}

}

Page 81: Spring

InjectRef.javapublic class InjectRef {

private Info info;

public void setInfo (Info info) {

Spring | Atul Kahate81

public void setInfo (Info info) {

this.info = info;

System.out.println(info.getInfo());

}

}

Page 82: Spring

ClientTester.javaimport org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.FileSystemResource;

public class ClientTester {

private String name;

private int age;

private float height;

private boolean isProgrammer;

Spring | Atul Kahate82

private boolean isProgrammer;

private Long ageInSeconds;

public static void main(String[] args) {

BeanFactory factory = new XmlBeanFactory(new FileSystemResource(

"beans2.xml"));

ClientTester simple = (ClientTester)factory.getBean("clientTester");

factory.getBean("injectRef");

System.out.println(simple);

}

public void setAgeInSeconds(Long ageInSeconds) {

this.ageInSeconds = ageInSeconds;

}

public void setIsProgrammer(boolean isProgrammer) {

this.isProgrammer = isProgrammer;

}

public void setAge(int age) {

this.age = age;

Page 83: Spring

beans2.xml<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<!-- injecting built-in vals sample -->

<bean id="clientTester" class="com.spring.simpleinjectbydi.ClientTester">

<property name="name">

<value>Kishore Kumar</value>

</property>

<property name="age">

<value>35</value>

</property>

<property name="height">

Spring | Atul Kahate83

<property name="height">

<value>67</value>

</property>

<property name="isProgrammer">

<value>true</value>

</property>

<property name="ageInSeconds">

<value>1103760000</value>

</property>

</bean>

<!-- oracle bean used for a few examples -->

<bean id="infobyid" name="infobyname" class="com.spring.simpleinjectbydi.InfoImpl"/>

<!-- injecting reference sample (using id) -->

<bean id="injectRef" class="com.spring.simpleinjectbydi.InjectRef">

<property name="info">

<ref local="infobyid"/>

</property>

</bean>

<!-- inject ref sample (using name) -->

Page 84: Spring

Bean Creation

Spring | Atul Kahate84

Page 85: Spring

Initializing and Destroying Beans

Spring | Atul Kahate85

Page 86: Spring

Bean initialization and destruction� It may be necessary to perform some initialization logic when a bean in instantiated

� Similarly, when a bean is to be destroyed, some clean up operations may be required

� We need to use the init-method and destroy-method parameters

Spring | Atul Kahate86

� We need to use the init-method and destroy-method parameters for our bean

� They specify the methods to be called during initialization and destruction, respectively

Page 87: Spring

beans4.xml<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="simpleBean1" class="com.spring.beaninitdestroy.SimpleBean" init-method="initOurBean" destroy-method="destroyOurBean">

<property name="name">

<value>Name overwritten!</value>

</property>

<property name="age">

<value>999</value>

Spring | Atul Kahate87

</property>

</bean>

<bean id="simpleBean2" class="com.spring.beaninitdestroy.SimpleBean" init-method="initOurBean" destroy-method="destroyOurBean">

<property name="age">

<value>999</value>

</property>

</bean>

<bean id="simpleBean3" class="com.spring.beaninitdestroy.SimpleBean" init-method="initOurBean">

<property name="name">

<value>Name overwritten!</value>

</property>

</bean>

</beans>

Page 88: Spring

SimpleBean.java/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package com.spring.beaninitdestroy;

import org.springframework.beans.factory.BeanCreationException;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.FileSystemResource;

public class SimpleBean {

Spring | Atul Kahate88

public class SimpleBean {

private static final String DEFAULT_NAME = "Atul Kahate";

private String name = null;

private int age = Integer.MIN_VALUE;

public void setName(String name) {

this.name = name;

}

public void setAge(int age) {

this.age = age;

}

public void initOurBean () {

System.out.println("Initializing bean");

if (name == null) {

System.out.println("Using default name");

name = DEFAULT_NAME;

Page 89: Spring

NetBeans package beanhierarchy

Hierarchical Processing

NetBeans package beanhierarchy

Spring | Atul Kahate89

Page 90: Spring

HierarchicalBeanFactoryUsage.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.beanhierarchy;

� /**

� *

� * @author atulk

� */

� import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

Spring | Atul Kahate90

� import org.springframework.beans.factory.xml.XmlBeanFactory;

� import org.springframework.core.io.FileSystemResource;

� public class HierarchicalBeanFactoryUsage {

� public static void main(String[] args) {

� BeanFactory parent = new XmlBeanFactory(new FileSystemResource(

� "parent.xml"));

� BeanFactory child = new XmlBeanFactory(new FileSystemResource(

� "beans5.xml"), parent);

� SimpleTarget target1 = (SimpleTarget) child.getBean("target1");

� SimpleTarget target2 = (SimpleTarget) child.getBean("target2");

� SimpleTarget target3 = (SimpleTarget) child.getBean("target3");

� System.out.println(target1.getVal());

� System.out.println(target2.getVal());

� System.out.println(target3.getVal());

� }

� }

Page 91: Spring

beans5.xml� <?xml version="1.0" encoding="UTF-8"?>

� <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

� <beans>

� <!-- hierarchical bean factories -->

� <bean id="target1" class="com.spring.beanhierarchy.SimpleTarget">

� <property name="val">

� <ref bean="injectBeanParent"/>

� </property>

� </bean>

� <bean id="target2" class="com.spring.beanhierarchy.SimpleTarget">

<property name="val">

Spring | Atul Kahate91

� <property name="val">

� <ref local="injectBean"/>

� </property>

� </bean>

� <bean id="target3" class="com.spring.beanhierarchy.SimpleTarget">

� <property name="val">

� <ref parent="injectBean"/>

� </property>

� </bean>

� <bean id="injectBean" class="java.lang.String">

� <constructor-arg>

� <value>Bean In Child</value>

� </constructor-arg>

� </bean>

� </beans>

Page 92: Spring

SimpleTarget.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.beanhierarchy;

� /**

� *

� * @author atulk

Spring | Atul Kahate92

� */

� public class SimpleTarget {

� private String val;

� public void setVal(String val) {

� this.val = val;

� }

� public String getVal() {

� return val;

� }

� }

Page 93: Spring

Specifying Bean Dependencies� The ref element is used to set the value of a property or a constructor argument to be a reference to another bean from the factory, or from a parent factory:� <ref local=“injectBean” />� <ref bean=“injectBean” />� <ref parent=“injectBean” />

Spring | Atul Kahate93

� <ref parent=“injectBean” />

� local, bean, and parent are mutually exclusive and must be the ID of another bean – they specify how to locate that referenced bean� local – Referred bean must be in the same XML file – parser validates this� bean - Referred bean can be in the same XML file or in a different XML file –Spring framework validates this

� parent – Referred bean must come from a parent factory to the current one

Page 94: Spring

Understanding the example – 1 � HierarchicalBeanFactoryUsage.java

� BeanFactory parent = new XmlBeanFactory(new FileSystemResource("parent.xml"));� Loads the parent.xml file

� BeanFactory child = new XmlBeanFactory(new

Spring | Atul Kahate94

BeanFactory child = new XmlBeanFactory(new FileSystemResource("beans5.xml"), parent);� Loads the beans5.xml file, with parent as its parent factory

Page 95: Spring

Understanding the example – 2� SimpleTarget target1 = (SimpleTarget) child.getBean("target1");

� Definition for this bean in beans5.xml is as follows:� <bean id="target1" class="com.spring.beanhierarchy.SimpleTarget">� <property name="val">� <ref bean="injectBeanParent"/>� </property>� </bean>

Spring | Atul Kahate95

</bean>� Indicates that injectBeanParent should be passed to it as a parameter� Definition of injectBeanParent in parent.xml is as follows:

� <bean id="injectBeanParent" class="java.lang.String">� <constructor-arg>� <value>Bean In Parent</value>� </constructor-arg>� </bean>

� Hence, a string Bean In Parent would be passed to the target1 bean

Page 96: Spring

Understanding the example – 3� SimpleTarget target2 = (SimpleTarget) child.getBean("target2");

� Definition for this bean in beans5.xml is as follows:� <bean id="target2" class="com.spring.beanhierarchy.SimpleTarget">� <property name="val">� <ref local="injectBean"/>� </property>� </bean>

� Indicates that injectBean should be passed to it as a parameter

Spring | Atul Kahate96

Indicates that injectBean should be passed to it as a parameter� Definition of injectBean is defined in the same XML file:

� <bean id="injectBean" class="java.lang.String">� <constructor-arg>� <value>Bean In Child</value>� </constructor-arg>� </bean>

� Hence, a string Bean In Child would be passed to the target1 bean� Note: injectBean is also defined in parent.xml. But it would be ignored, as we

have specified injectBean also in the local file (beans5.xml) and we have used ref local in the target2 definition

Page 97: Spring

Understanding the example – 4� Note: injectBean is also defined in parent.xml. But it would be ignored, as we have specified injectBean also in the local file (beans5.xml) and we have used ref local in the target2 definition� Carrying this forward, now do the following changes in beans5.xml and see if the

result changes – why?� <bean id="target2" class="com.spring.beanhierarchy.SimpleTarget">� <property name="val">� <ref bean="injectBean"/>

Spring | Atul Kahate97

� <ref bean="injectBean"/>� </property>� </bean>

� AND� <!-- <bean id="injectBean" class="java.lang.String">� <constructor-arg>� <value>Bean In Child</value>� </constructor-arg>� </bean> -->

Page 98: Spring

Understanding the example – 5� SimpleTarget target3 = (SimpleTarget) child.getBean("target3");

� Definition for this bean in beans5.xml is as follows:� <bean id="target3" class="com.spring.beanhierarchy.SimpleTarget">� <property name="val">� <ref parent="injectBean"/>� </property>� </bean>

� Indicates that injectBean must be obtained from parent factory – ignore local

Spring | Atul Kahate98

� Indicates that injectBean must be obtained from parent factory – ignore local instance of injectBean, if exists

� Definition of injectBean from parent.xml file:� <bean id="injectBean" class="java.lang.String">� <constructor-arg>� <value>Bean In Parent</value>� </constructor-arg>� </bean>

� Hence, a string Bean In Parent would be passed to the target1 bean

Page 99: Spring

Spring AOP

Spring | Atul Kahate99

Page 100: Spring

Need for AOP� Aspect-oriented programming (AOP) provides for simplified application of cross-cutting concerns

� Examples of cross-cutting concerns� Logging

� Transaction management

Spring | Atul Kahate100

� Transaction management

� Security

� Auditing

� Locking

� Event handling

Page 101: Spring

AOP Illustrated

Spring | Atul Kahate101

Page 102: Spring

Need for AOP – A Case Study

Spring | Atul Kahate102

Page 103: Spring

Account Case Study� Suppose we want to develop a class that has two methods that allow depositing and withdrawing of money to and from a bank account

� Sample implementation on next page

Spring | Atul Kahate103

Page 104: Spring

Account Class – Sample Implementationpublic class Account{public long deposit(long depositAmount){newAmount = existingAmount + depositAmount;currentAmount = newAmount;return currentAmount;

}

Spring | Atul Kahate104

public long withdraw(long withdrawalAmount){if (withdrawalAmount <= currentAmount){currentAmount = currentAmount – withdrawalAmount;

}return currentAmount;

}}

Page 105: Spring

Need to Add Security� Suppose we now want to ensure that only the administrator user can perform the deposit and withdrawal transactions

� Hence, we need to first check which user is invoking these methods and then allow/disallow based on the user type/role

Spring | Atul Kahate105

type/role

� Suppose we have a User class that returns the user id, by calling the appropriate method

� We can modify our implementation as shown next

Page 106: Spring

Modified Account Classpublic class Account{

public long deposit(long depositAmount){

User user = User.getUser();

if (user.getRole().equals("BankAdmin"){

newAmount = existingAccount + depositAccount;

currentAmount = newAmount;

}

Spring | Atul Kahate106

}

return currentAmount;

}

public long withdraw(long withdrawalAmount){

User user = User.getUser();

if (user.getRole().equals("BankAdmin"){

if (withdrawalAmount <= currentAmount){

currentAmount = currentAmount – withdrawalAmount;

}

}

return currentAmount;

}

}

Page 107: Spring

Need to Add Transaction and Logging

Capabilities

� Suppose now we want to add transaction support and logging support to our Account class

� Modified code shown next

Spring | Atul Kahate107

Page 108: Spring

Modified Account Classpublic class Account{

public long deposit(long depositAmount){

logger.info("Start of deposit method");

Transaction trasaction = Transaction.getTransaction();

transaction.begin();

try{

User user = User.getUser();

if (user.getRole().equals("BankAdmin"){

newAmount = existingAccount + depositAccount;

currentAmount = newAmount;

}

transaction.commit();

}catch(Exception exception){

Spring | Atul Kahate108

}catch(Exception exception){

transaction.rollback();

}

logger.info("End of deposit method");

return currentAmount;

}

public long withdraw(long withdrawalAmount){

logger.info("Start of withdraw method");

Transaction trasaction = Transaction.getTransaction();

transaction.begin();

try{

User user = User.getUser();

if (user.getRole().equals("BankAdmin"){

if (withdrawalAmount <= currentAmount){

currentAmount = currentAmount – withdrawalAmount;

}

}

transaction.commit();

}catch(Exception exception){

transaction.rollback();

Page 109: Spring

Observations� As we can see, as we keep on making changes to our code, it becomes more and more complex

� Involves re-testing of the entire code

� Actual business logic is very small – the other aspects consume majority of code and logic

Spring | Atul Kahate109

consume majority of code and logic

� Can this be avoided?

� Let us revisit what our code is actually doing step-by-step

Page 110: Spring

Steps in Our Codepublic void deposit(){

// Transaction Management

// Logging

// Checking for the Privileged User

// Actual Deposit Logic comes here

}

Spring | Atul Kahate110

}

public void withdraw(){

// Transaction Management

// Logging

// Checking for the Privileged User

// Actual Withdraw Logic comes here

}

Page 111: Spring

Enter AOP� In AOP terms, these aspects such as transaction management, user role checking, logging, etc should be separated into separate blocks of code

� Our actual code should just concentrate on the business logic

� See next slide

Spring | Atul Kahate111

� See next slide

Page 112: Spring

These are aspectspublic void businessOperation(BusinessData data){

// Logginglogger.info("Business Method Called");

// Transaction Management Begintransaction.begin();

Spring | Atul Kahate112

transaction.begin();

// Do the original business operation here……

// Transaction Management Endtransaction.end();

}

Page 113: Spring

Join Points – Places where we can look

for Aspectspublic void someBusinessOperation(BusinessData data){

//Method Start -> Possible aspect code here like logging.

try{

// Original Business Logic here.

}catch(Exception exception){

// Exception -> Aspect code here when some exception is raised.

Spring | Atul Kahate113

// Exception -> Aspect code here when some exception is raised.

}finally{

// Finally -> Even possible to have aspect code at this point too.

}

// Method End -> Aspect code here in the end of a method.

}

Page 114: Spring

Pointcut – Join Point where an Aspect

would actually be appliedpointcut method_start_end_pointcut(){

// This point cut applies the aspects, logging and transaction, before the // beginning and the end of the method.

}

Spring | Atul Kahate114

pointcut catch_and_finally_pointcut(){

// This point cut applies the aspects, logging and transaction, in the catch // block (whenever an exception raises) and the finally block.

}

Page 115: Spring

Advice� We can roughly say that Aspect is the concept, which is implemented by an Advice

� Aspect is abstract, Advice is concrete

� Following Advice types are supported in Spring:� Before Advice

Spring | Atul Kahate115

� Before Advice

� After Advice

� Throws Advice

� Around Advice

Page 116: Spring

Before Advice� Intercepts a method before it starts execution

� The org.springframework.aop.BeforeAdvice interface is used to represent this

� Example: Authenticate the user before allowing the user to perform deposit or withdraw transaction

Spring | Atul Kahate116

perform deposit or withdraw transaction

Page 117: Spring

After Advice� Intercepts a method before it returns control back to the caller

� The org.springframework.aop.AfterReturningAdviceinterface is used to represent this

� Example: Delete session data before sending control back to

Spring | Atul Kahate117

� Example: Delete session data before sending control back to the caller

Page 118: Spring

Throws Advice� Intercepts a method when it attempts to throw an exception

� The org.springframework.aop.ThrowsAdvice interface is used to represent this

� Example: Delete session data before sending control back to the caller

Spring | Atul Kahate118

the caller

Page 119: Spring

Around Advice� Provides finer control over the execution of a method

� The org.aopalliance.intercept.MethodInterceptor interface is used to represent this

� Example: Delete session data before sending control back to the caller

Spring | Atul Kahate119

the caller

Page 120: Spring

NetBeans package com.spring.empwithoutaop

AOP Case Study

NetBeans package com.spring.empwithoutaop

Spring | Atul Kahate120

Page 121: Spring

Requirement� We need to represent the details of an employee

� We can create an Employee interface that captures the essential details of the employee and a concrete class named EmployeeImpl that implements this interface

� We can then use the standard new approach to create an

Spring | Atul Kahate121

� We can then use the standard new approach to create an instance of EmployeeImpl

Page 122: Spring

Employee.javapublic interface Employee {

public String getFirstName();

public void setFirstName(String FirstName);

public String getLastName();

public void setLastName(String LastName);

Spring | Atul Kahate122

public String getJobTitle();

public void setJobTitle(String JobTitle);

public Float getSalary();

public void setSalary(Float Salary);

public Date getHiredate();

public void setHiredate(Date Hiredate);

}

Page 123: Spring

EmployeeImpl.java/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package com.spring.empwithoutaop;

import java.util.Date;

/**

*

* @author atulk

*/

import java.util.Date;

Spring | Atul Kahate123

import java.util.Date;

public class EmployeeImpl implements Employee {

String FirstName;

String LastName;

String JobTitle;

Float Salary;

Date Hiredate;

public EmployeeImpl() {

}

public String getFirstName() {

return FirstName;

}

public void setFirstName(String FirstName) {

this.FirstName = FirstName;

}

public String getLastName() {

Page 124: Spring

Client.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.empwithoutaop;

� /**

� *

� * @author atulk

� */

� public class Client {

public Client() {

Spring | Atul Kahate124

� public Client() {

� }

� public Employee getEmployee() {

� Employee emp = new EmployeeImpl();

� return emp;

� }

� public static void main(String[] args) {

� Client client = new Client();

� Employee employee = client.getEmployee();

� employee.setFirstName("Ram");

� employee.setLastName("Shastri");

� employee.setJobTitle("SALESMAN");

� employee.setSalary(new Float("5000"));

� System.out.println("The new salary for " + employee.getFirstName() + " " + employee.getLastName() + " (" + employee.getJobTitle() + ") = " + employee.getSalary());

� }

� }

Page 125: Spring

New Business Rules� Now suppose there were some business rules that needed to be applied:� A Salesman may not earn more than 4000

� Ram Shastri is not an acceptable name for an employee

� If we have source code, we can make changes – even then it is

Spring | Atul Kahate125

� If we have source code, we can make changes – even then it is not easy

� If we do not have source code but have just the JAR, things are worse

� AOP can help resolve this easily

Page 126: Spring

Using ProxyFactory� Instead of getting hold of an EmployeeImpl object, we have a Spring ProxyFactory intervene and

wrap the EmployeeImpl in a proxy object.

� We let the proxy intercept calls to setter methods, verify their validity and throw an exception for incorrect values

� When the validation succeeds, the setter method on the EmployeeImpl object is invoked as we intended all along.

� For this, we need a class that implements the Spring MethodBeforeAdvice interface. We can inject this class into the ProxyFactory; this instructs the ProxyFactory to intercept any call to methods on the EmployeeImpl object and call the before() method on the MethodBeforeAdvice before

Spring | Atul Kahate126

the EmployeeImpl object and call the before() method on the MethodBeforeAdvice before continuing with the original call to the EmployeeImpl method.

� So in short, the steps are: � Specify the Employee “domain interface” � Acquire implementation of the Employee Interface (EmployeeImpl) � Create an implementation of the MethodBeforeAdvice interface that handles Validation of Business

Rules in its before method � Have the application invoke the Spring AOP ProxyFactory to return a proxy wrapping the Employee

instance, after instructing the ProxyFactorythat the MethodBeforeAdvice should be applied to the proxy

� From the application, Invoke the getters and setters on the Employee instance - the proxiedEmployeeImpl

Page 127: Spring

New Class – EmployeeValidator.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.empwithoutaop;

� import org.springframework.aop.MethodBeforeAdvice;

� import java.lang.reflect.Method;

� public class EmployeeValidator implements MethodBeforeAdvice {

� public EmployeeValidator() {}

Spring | Atul Kahate127

� public void before(Method method, Object[] args, Object target) throws Throwable {

� Employee emp = (EmployeeImpl) target;

� if (method.getName().equalsIgnoreCase("setSalary")) {

� if ("SALESMAN".equalsIgnoreCase(emp.getJobTitle())) {

� // if the job of this employee is SALESMAN, he/she may not earn more than 4000

� float newSalary = ((Float) args[0]).floatValue();

� if (newSalary > 4000) {

� throw new RuntimeException("Salary may not exceed 4000 for Salesmen such as " + emp.getFirstName() + " " + emp.getLastName());

� }

� }

� }

� if (method.getName().equalsIgnoreCase("setFirstName")) {

� if ("Ram".equalsIgnoreCase(emp.getLastName())) {

� // we do not want any employee to be called John Doe

� if ("Shastri".equalsIgnoreCase((String) args[0])) {

� throw new RuntimeException("Employees should not be called Ram Shastri. Choose another First Name please.");

� }

� }

� }

� if (method.getName().equalsIgnoreCase("setLastName")) {

� if ("Ram".equalsIgnoreCase(emp.getFirstName())) {

Page 128: Spring

New Client – ClientWithAOP.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.spring.empwithoutaop;

� import org.springframework.aop.framework.ProxyFactory;

� public class ClientWithAOP {

� public Employee getEmployee() {

� Employee emp = new EmployeeImpl();

ProxyFactory pf = new ProxyFactory();

Spring | Atul Kahate128

� ProxyFactory pf = new ProxyFactory();

� pf.setTarget(emp);

� pf.setInterfaces(new Class[]{Employee.class}); // this line is required for using the JDK 1.3 proxy based Spring AOP implementation,

� //otherwise the CGLib libraries are required

� pf.addAdvice(new EmployeeValidator());

� return (Employee) pf.getProxy();

� }

� public ClientWithAOP() {

� }

� public static void main(String[] args) {

� ClientWithAOP client = new ClientWithAOP();

� Employee employee = client.getEmployee();

� employee.setFirstName("Rahul");

� employee.setLastName("Dravid");

� employee.setJobTitle("SALESMAN");

� employee.setSalary(new Float("5000"));

� System.out.println("The new salary for " + employee.getFirstName() + " " + employee.getLastName() + " (" + employee.getJobTitle() + ") = " + employee.getSalary());

� }

� }

Page 129: Spring

AOP Revision

Spring | Atul Kahate129

Page 130: Spring

AOP Joinpoint� Point in the control flow of a program

� We can identify Joinpoints and insert additional logic at those Joinpoint's

� Examples of Jointpoint's (place at which the main logic meets with aspects such as logging, transaction, security, etc)

Spring | Atul Kahate130

with aspects such as logging, transaction, security, etc)� Method invocation

� Class initialization

� Object initialization

� Set of Joinpoints creates a pointcut

Page 131: Spring

AOP Advice� The code that is executed at a particular joinpoint

� That is, specifies what to do at a join point� Some additional behavior that Spring injects around a method invocation, defined in a method interceptor

� Types of Advice

Spring | Atul Kahate131

� Types of Advice� before advice, which executes before joinpoint

� after advice, which executes after joinpoint

� around advice, which executes around joinpoint

Page 132: Spring

AOP Pointcuts� A collection of joinpoints that we use to define when advice should be executed

� By creating pointcuts, you gain fine-grained control over how we apply advice to the components

� Example

Spring | Atul Kahate132

� Example� A typical joinpoint is a method invocation.

� A typical pointcut is a collection of all method invocations in a particular class

� Pointcuts can be composed in complex relationships to further constrain when advice is executed

Page 133: Spring

AOP Aspect� An aspect is the combination of advice and pointcuts

Spring | Atul Kahate133

Page 134: Spring

AOP Weaving� Process of actually inserting aspects into the application code at the appropriate point

� Types of Weaving� Compile time weaving

� Runtime weaving

Spring | Atul Kahate134

� Runtime weaving

Page 135: Spring

AOP Target� An object whose execution flow is modified by some AOP process

� They are sometimes called advised object

Spring | Atul Kahate135

Page 136: Spring

Implementing AOP� Process by which you can modify the structure of an object by introducing additional methods or fields to it

� You use the Introduction to make any object implement a specific interface without needing the object's class to implement that interface explicitly

Spring | Atul Kahate136

implement that interface explicitly

Page 137: Spring

Types of AOP� Static AOP

� The weaving process forms another step in the build process for an application

� Example: In Java program, you can achieve the weaving process by modifying the actual bytecode of the application changing

Spring | Atul Kahate137

by modifying the actual bytecode of the application changing and modifying code as necessary

� Dynamic AOP� The weaving process is performed dynamically at runtime

� Easy to change the weaving process without recompilation

Page 138: Spring

AOP Implementation Details� Based on proxies

� When we want to create an advised instance of a class, we must use the ProxyFactory class to create a proxy of an instance of that class, first providing the ProxyFactory with all the aspects that we want to be woven into the proxy

Spring | Atul Kahate138

� We typically use ProxyFactoryBean class to provide declarative proxy creation

Page 139: Spring

com.spring.aophelloworld

AOP Hello World Example

com.spring.aophelloworld

Spring | Atul Kahate139

Page 140: Spring

IMessageWriter.java� package com.spring.aophelloworld;

� /**� *� * @author atulk

Spring | Atul Kahate140

� * @author atulk� */� public interface IMessageWriter {

� public void writeMessage();� }

Page 141: Spring

MessageWriter.java� package com.spring.aophelloworld;

� /**� *� * @author atulk� */

Spring | Atul Kahate141

� */� public class MessageWriter implements IMessageWriter{

� public void writeMessage() {� System.out.print("World");� }

� }

Page 142: Spring

MessageDecorator.java� package com.spring.aophelloworld;

� /**

� *

� * @author atulk

� */

� import org.aopalliance.intercept.MethodInterceptor;

� import org.aopalliance.intercept.MethodInvocation;

Spring | Atul Kahate142

� public class MessageDecorator implements MethodInterceptor {

� public Object invoke(MethodInvocation invocation) throws Throwable {

� System.out.print("Hello ");

� Object retVal = invocation.proceed();

� System.out.println("!");

� return retVal;

� }

� }

Page 143: Spring

HelloWorldAOPExample.java� package com.spring.aophelloworld;

� import org.springframework.aop.framework.ProxyFactory;

� public class HelloWorldAOPExample {

� public static void main(String[] args) {

� MessageWriter target = new MessageWriter();

� // create the proxy

� ProxyFactory pf = new ProxyFactory();

Spring | Atul Kahate143

� pf.addAdvice(new MessageDecorator());

� pf.setTarget(target);

� MessageWriter proxy = (MessageWriter) pf.getProxy();

� // write the messages

� target.writeMessage();

� System.out.println("");

� proxy.writeMessage();

� }

� }

Page 144: Spring

Integrating JSF with Spring

Spring | Atul Kahate144

Page 145: Spring

Requirements for Integrating JSF with

Spring – 1� In the faces-config.xml file, we need to add the following:<application> <variable-resolver> org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>

</application>

Spring | Atul Kahate145

</application>� The web.xml should have the following entry:<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

Page 146: Spring

Requirements for Integrating JSF with

Spring – 2� Code the Spring bean and have an interface for it (ideally):

� Example:

public interface TimeService { Date getNow ();

}

Spring | Atul Kahate146

}

public class TimeServiceImpl implements TimeService { public Date getNow () {return new Date ();

}}

Page 147: Spring

Requirements for Integrating JSF with

Spring – 3� Add an entry in the applicationContext.cml file for our Spring bean:

<bean id="timeService"

class="com.source.timeservice.TimeServiceImpl" />

Spring | Atul Kahate147

Page 148: Spring

Requirements for Integrating JSF with Spring – 4

… Code our JSF bean that uses the Spring bean

public class UiBean implements InitializingBean {

private TimeService timeService = null;

public String getShortDate() {

return SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT).format(

getTimeService().getNow());

}

Spring | Atul Kahate148

}

public TimeService getTimeService() {

return timeService;

}

public void setTimeService(TimeService timeService) {

this.timeService = timeService;

}

}

Page 149: Spring

Requirements for Integrating JSF with

Spring – 5 … faces-config file<managed-bean>

<managed-bean-name>userBean</managed-bean-name>

<managed-bean-class>com.source.timeservice.UserBean</managed-bean-class>

<managed-bean-scope>request</managed-bean-scope>

<managed-property>

<property-name>timeService</property-name>

Spring | Atul Kahate149

<property-name>timeService</property-name>

<value>#{timeService}</value>

</managed-property>

</managed-bean>

� Note: We are passing the Spring bean to the JSF bean as a property, the way we normally do in Spring (DI feature)

Page 150: Spring

Requirements for Integrating JSF with

Spring – 6 … time.jsp file<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %><%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %><f:view><html><head><title>jsf-spring quickstart</title>

Spring | Atul Kahate150

<title>jsf-spring quickstart</title></head><body><h:outputText value="#{userBean.shortDate}"/></body></html></f:view>

Page 151: Spring

JSF with Spring – Another Example

Spring | Atul Kahate151

Page 152: Spring

Example 1 – stockInput.jsp� <%@page contentType="text/html"%>

� <%@page pageEncoding="UTF-8"%>

� <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>

� <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

� <f:view>

� <html>

� <head>

� <title>

� Stock Input Page

</title>

Spring | Atul Kahate152

� </title>

� </head>

� <body>

� <h:form id="stockForm">

� <h1>

� Please Enter the Stock Symbol and click the button

� </h1>

� <p>

� <h:inputText id="stockSymbolInput" value="#{stockBean.symbolName}"

� required="true">

� </h:inputText>

� </p>

� <h:commandButton id="stockSubmit" type="submit" value="Submit Symbol"

� action="#{stockBean.findStockValue}">

� </h:commandButton>

� </h:form>

� </body>

Page 153: Spring

Example 1 – stockOutputSuccess.jsp� <%@page contentType="text/html"%>

� <%@page pageEncoding="UTF-8"%>

� <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>

� <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

� <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

� "http://www.w3.org/TR/html4/loose.dtd">

� <html>

� <head>

� <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

Spring | Atul Kahate153

� <title>JSP Page</title>

� </head>

� <body>

� <f:view>

� <h1>

� The Stock Value of the symbol

� <h:outputText value="#{stockBean.symbolName}"> </h:outputText>

� is

� <h:outputText value="#{stockBean.symbolValue}"> </h:outputText>

� </h1>

� </f:view>

� </body>

� </html>

Page 154: Spring

Example 1 – stockOutputFailure.jsp� <%@page contentType="text/html"%>

� <%@page pageEncoding="UTF-8"%>

� <%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>

� <%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

� <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

� "http://www.w3.org/TR/html4/loose.dtd">

� <html>

� <head>

� <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Spring | Atul Kahate154

� <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

� <title>JSP Page</title>

� </head>

� <body>

� <f:view>

� <h1>

� The Stock symbol

� <h:outputText value="#{stockBean.symbolName}"> </h:outputText>

� is not found. Please check again.

� </h1>

� </f:view>

� </body>

� </html>

Page 155: Spring

Example 1 – StockValueFetcher.java� /*

� * To change this template, choose Tools | Templates

� * and open the template in the editor.

� */

� package com.source.springwithjsf;

� /**

� *

� * @author atulk

� */

� import java.util.*;

Spring | Atul Kahate155

� public class StockValueFetcher {

� private Map<String, String> stockSymbolsAndValues;

� private String symbolName;

� private String symbolValue;

� public StockValueFetcher() {

� stockSymbolsAndValues = new HashMap<String, String>();

� stockSymbolsAndValues.put("ABC", "10");

� stockSymbolsAndValues.put("DEF", "20");

� stockSymbolsAndValues.put("GHI", "30");

� stockSymbolsAndValues.put("JKL", "40");

� }

� public String getSymbolName() {

� return symbolName;

� }

� public void setSymbolName(String symbolName) {

� this.symbolName = symbolName;

Page 156: Spring

Example 1 – faces.config.xml� <?xml version='1.0' encoding='UTF-8'?>

� <!-- =========== FULL CONFIGURATION FILE ================================== -->

� <faces-config version="1.2"

� xmlns="http://java.sun.com/xml/ns/javaee"

� xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

� xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">

� <application>

� <variable-resolver>

� org.springframework.web.jsf.DelegatingVariableResolver

</variable-resolver>

Spring | Atul Kahate156

� </variable-resolver>

� </application>

� <managed-bean>

� <managed-bean-name>stockBean</managed-bean-name>

� <managed-bean-class>

� com.source.springwithjsf.StockValueFetcher

� </managed-bean-class>

� <managed-bean-scope>request</managed-bean-scope>

� </managed-bean>

� <managed-bean>

� <managed-bean-name>accountBean</managed-bean-name>

� <managed-bean-class>

� com.source.springwithjsf.AccountBean

� </managed-bean-class>

� <managed-bean-scope>request</managed-bean-scope>

� </managed-bean>

� <navigation-rule>

� <description>Navigation from the hello page.</description>

Page 157: Spring

JSF with Spring – Another Example

Spring | Atul Kahate157

Page 158: Spring

Example 2 – enterAccountNumber.jsp� <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

� <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

� <html>

� <head>

� <title>JSF with Spring</title>

� </head>

� <body>

� <f:view>

� <h:form>

� <table width="30%" height="30%" border="2" cellspacing="0" cellpadding="5">

� <tr>

<td colspan="2">

Spring | Atul Kahate158

� <td colspan="2">

� <h:message for="accountNumber" />

� </td>

� </tr>

� <tr>

� <td>

� <h:inputText id="accountNumber" value="#{accountBean.accountNumber}"/>

� </td>

� <td><b>

� <h:outputText value="Account Number"/>

� </b></td>

� </tr>

� <tr>

� <td colspan="2">

� <h:commandButton action="#{accountBean.findAccountBalance}" value="Get Balance"/>

� </td>

� </tr>

� <tr>

� <td>

� <h:outputText value="#{accountBean.balance}"/>

� </td>

� <td><b>

Page 159: Spring

Example 2 – AccountNumberBean.java� /*

� * PageBean.java

� *

� * Created on September 20, 2007, 5:28 PM

� *

� * To change this template, choose Tools | Template Manager

� * and open the template in the editor.

� */

� package com.source.springwithjsf;

� import java.util.HashMap;

� import java.util.Map;

Spring | Atul Kahate159

� public class AccountBean {

� private String accountNumber;

� private String balance;

� private Map<String, String> accountMap;

� public AccountBean() {

� accountMap = new HashMap<String, String>();

� accountMap.put("1", "1000");

� accountMap.put("2", "2000");

� accountMap.put("3", "3000");

� accountMap.put("4", "4000");

� accountMap.put("5", "5000");

� accountMap.put("6", "6000");

� accountMap.put("7", "7000");

� }

� public String getAccountNumber() {

� return accountNumber;

� }