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 />

@Configuration<br />

@ComponentScan<br />

public class Application {<br />

@Bean<br />

MessageService helloWorldMessageService() {<br />

return new HelloWorldMessage();<br />

}<br />

public static void main(String[] args) {<br />

ApplicationContext context =<br />

new AnnotationConfigApplicationContext(Application.class);<br />

}<br />

}<br />

MessageService service =<br />

context.getBean(MessageService.class);<br />

System.out.println(service.getMessage());<br />

You must have Gradle installed, because this tool will help you to compile, build, and run all your examples.<br />

The following command will run the example. Also remember that this command should be executed from the root<br />

of the project where the build.gradle file is located.<br />

gradle run -DmainClass=com.apress.isf.spring.Application<br />

Running the above command should output something similar to the following:<br />

isf-book$ gradle run -DmainClass=com.apress.isf.spring.Application<br />

:ch01:compileJava UP-TO-DATE<br />

:ch01:compileGroovy UP-TO-DATE<br />

:ch01:processResources UP-TO-DATE<br />

:ch01:classes UP-TO-DATE<br />

:ch01:run<br />

20:37:08.705 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of<br />

singleton bean 'helloWorldMessageService'<br />

Hello World<br />

■ ■Note You can also run the gradle command from the project base by just adding the chapter’s folder, like so:<br />

$ gradle :ch01:run –DmainClass=com.apress.isf.spring.Application.<br />

The <strong>Spring</strong> <strong>Framework</strong> is based on one simple principle: dependency injection. This is a design pattern that<br />

has been around for several years; it works, based on interface design, by injecting through setters or constructors<br />

all of the dependencies and implementations that have collaboration and interaction among classes. The <strong>Spring</strong><br />

<strong>Framework</strong> creates a container that can handle all of this interaction and collaboration between objects.<br />

This simple example defines an interface. In the main class, you are injecting its implementation by using the<br />

@Bean annotation over the helloWorldMessageService method. This will tell the <strong>Spring</strong> <strong>Framework</strong> container that<br />

the HelloWorldMessage class is the implementation and it will be used at some point.<br />

7

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

Saved successfully!

Ooh no, something went wrong!