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 4 ■ Using Beans Scopes<br />

documentDAO(DocumentRepository){ bean -><br />

bean.scope = "prototype"<br />

doc1 = ref("doc1")<br />

doc2 = ref("doc2")<br />

doc3 = ref("doc3")<br />

doc4 = ref("doc4")<br />

}<br />

}<br />

//More bean definitions omitted.<br />

Listing 4-6 shows your Groovy script: mydocuments.groovy. Now you are using a variable to define the scope.<br />

You don’t need to worry too much about the correct syntax for this Groovy configuration; you are going to see it in<br />

detail in Chapter 18.<br />

Running the test, you should get the same results: two different instances of the SearchEngine class<br />

implementation (SearchEngineService) and two different instances of the DocumentDAO class implementation<br />

(DocumentRepository). But what happens if you combine bean scopes between dependencies? Well, this is an<br />

exercise that you can do as homework. You need to put in more logs in order to find out what is happening.<br />

■ ■Note In the book’s source code, you will find all the tests and classes that have been modified for this chapter.<br />

You can use this source code to do your homework, right?<br />

Summary<br />

In this chapter, you added logs to some constructors and methods to discover how the <strong>Spring</strong> container works.<br />

You saw that by default the <strong>Spring</strong> container will create a single instance because the scope is a singleton, and every<br />

time you get that bean you are going to have the same instance. If you change the scope of your beans to prototype,<br />

every time you get your bean, the <strong>Spring</strong> container will create a new fresh instance of your class. In the book’s<br />

companion source code, you can find the complete examples using the Java bean configuration, XML, annotations,<br />

and the GroovyBeanDefinitionReader.<br />

52

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

Saved successfully!

Ooh no, something went wrong!