Wiley Beginning Spring Framework 2 978-0-470-10161-2 Manual De Usuario

Los códigos de productos
978-0-470-10161-2
Descargar
Página de 28
wired components can be Java objects that you have written for the application, or one of the many pre-
fabricated components in the Spring API library (or a component from a third-party vendor, such as a
transaction manager from Hibernate).
It is of paramount importance, then, to understand how components instantiation and wiring work in
Spring. There is no better way to show how Spring object wiring works than through an actual example. 
The Spring framework works with modularized applications. The first step is to create such an applica-
tion. The next section shows you how to start with an all-in-one application and break it down into com-
ponents. Then you can see how Spring adds value by flexibly wiring together the components.
Creating a Modularized Application
Consider a simple application to add two numbers and print the result.
The entire application can be created within one single class called 
Calculate
. The following code
shows this monolithic version:
package com.wrox.begspring;
public class Calculate {
public Calculate() {}
public static void main(String[] args) {
Calculate calc = new Calculate();
calc.execute(args);
}
private void showResult(String result)  {
System.out.println(result);
}
private long operate(long op1, long op2)  {
return op1 + op2;
}
private String getOpsName() {
return “ plus “;
}
public void execute(String [] args)  {
long op1 = Long.parseLong(args[0]);
long op2 = Long.parseLong(args[1]);
showResult(“The result of “ + op1 +  
getOpsName() + op2 + “ is “
+ operate(op1, op2) + “!”);
}
}
For example, if you need to perform multiplication instead of addition on the operation, the code to calcu-
late must be changed. If you need to write the result to a file instead of to the screen, the code must be
changed again. This application can readily be modularized to decouple the application logic from the
3
Chapter 1: Jump Start Spring 2
01612c01.qxd:WroxPro  10/31/07  10:42 AM  Page 3