Putting a Spring into "Hello World!"
We hope by this point in the topic you appreciate that Spring is a solid, well-supported project that
has all the makings of a great tool for application development. However, one thing is missing--we
haven't shown you any code yet. We are sure you are dying to see Spring in action, and because we
cannot go any longer without getting into the code, let's do just that. Do not worry if you do not fully
understand all the code in this section; we go into much more detail on all the topics as we proceed
through the topic.
Building the Sample "Hello World!"Application
Now, we are sure you are familiar with the traditional "Hello World!" example, but just in case you have
been living on the moon for the past 30 years, Listing 2-1 shows the Java version in all its glory.
Listing 2-1. Typical "Hello World!"Example
package com.apress.prospring3.ch2;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
As far as examples go, this one is pretty simple--it does the job, but it is not very extensible. What if
we want to change the message? What if we want to output the message differently, maybe to stderr
instead of stdout or enclosed in HTML tags rather than as plain text?
We are going to redefine the requirements for the sample application and say that it must support a
simple, flexible mechanism for changing the message, and it must be simple to change the rendering
behavior. In the basic "Hello World!"example, you can make both of these changes quickly and easily by
just changing the code as appropriate. However, in a bigger application, recompiling takes time, and it
requires the application to be fully tested again. No, a better solution is to externalize the message
content and read it in at runtime, perhaps from the command-line arguments shown in Listing 2-2.
Listing 2-2. Using Command-Line Arguments with "Hello World!"
package com.apress.prospring3.ch2;
public class HelloWorldWithCommandLine {
public static void main(String[] args) {
if(args.length > 0) {
System.out.println(args[0]);
} else {
System.out.println("Hello World!");
}
}
}
This example accomplishes what we wanted--we can now change the message without changing
the code. However, there is still a problem with this application: the component responsible for
rendering the message is also responsible for obtaining the message. Changing how the message is
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home