25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 1 ■ Your First <strong>Spring</strong> Application<br />

Listing 1-2 shows a simple Interface with only one method.<br />

Listing 1-2. MessageService.java<br />

package com.apress.isf.spring;<br />

public interface MessageService {<br />

public String getMessage();<br />

}<br />

Next, let’s create the HelloWorldMessage that will return just the simple “Hello World” (see Listing 1-3).<br />

Listing 1-3. HelloWorldMessage.java<br />

package com.apress.isf.spring;<br />

public class HelloWorldMessage implements MessageService {<br />

}<br />

public String getMessage(){<br />

return "Hello World";<br />

}<br />

Listing 1-3 shows the implementation of the interface in Listing 1-2. You can make any implementation you want<br />

if you keep following the contract that your interface provides. For example, right now you just return a string, but you<br />

can actually call a service or go into a database and pick a random message.<br />

■ ■Note All of these examples can be edited using any text editor or any favorite IDE (integrated development<br />

environment).<br />

Now you are ready to test your implementation, but you need to add a starting point.<br />

Running the Hello World Application<br />

Listing 1-4 shows the main class where you are going to test your MessageService class implementation (Listing 1-3,<br />

the HelloWorldMessage class). Now you need to take a look at Listing 1-4, because I am introducing some annotations<br />

(annotations were introduced as a new feature in Java 5). These annotations are markers for the <strong>Spring</strong> <strong>Framework</strong> to<br />

help understand your classes and they collaborate together. But wait! <strong>Spring</strong> <strong>Framework</strong>? Right now you are going to<br />

run this example as it is; later in this and the following chapter, you will learn what the <strong>Spring</strong> <strong>Framework</strong> is and how it<br />

can help you to deliver enterprise-ready applications.<br />

Listing 1-4. Application.java<br />

package com.apress.isf.spring;<br />

import org.springframework.context.ApplicationContext;<br />

import org.springframework.context.annotation.Bean;<br />

import org.springframework.context.annotation. AnnotationConfigApplicationContext;<br />

6

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!