25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4 ■ Using Beans Scopes<br />

The result is one SearchEngineService instance and one DocumentDAO instance (your concrete class,<br />

DocumentRespository). But why? Remember that by default the <strong>Spring</strong> <strong>Framework</strong> only creates a Singleton<br />

instance of your bean, so even if you call this bean (with the getBean method) several times, you are going to get<br />

the same instance.<br />

Now, let’s modify the XML and how the <strong>Spring</strong> container uses the bean scopes. See Listing 4-3 for the XML<br />

configuration.<br />

Listing 4-3. mydocuments-context.xml<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

In Listing 4-3, you added the scope prototype attribute to the beans engine and documentDAO. The <strong>Spring</strong><br />

container will create a new instance of these classes once the getBean method from the application context is called.<br />

If you run the test again, you will see the following output:<br />

$ gradle –Dtest.simple=MyDocumentTest test<br />

DEBUG [main] ServiceSearchEngine created: com.apress.isf.spring.service.ServiceSearchEngine@2ac1d29e<br />

DEBUG [main] Document DAO set: com.apress.isf.spring.data.DocumentRepository@702557dd<br />

DEBUG [main] ServiceSearchEngine created: com.apress.isf.spring.service.ServiceSearchEngine@23aba7b0<br />

DEBUG [main] Document DAO set: com.apress.isf.spring.data.DocumentRepository@5a8e261b<br />

As you can see, now you have different instances because you call the method getBean twice for the engine and<br />

every time you get a new instance; the same happens for the documentDAO setter.<br />

Table 4-1 shows how the Bean Scopes are handled by the <strong>Spring</strong> container. These scopes can be defined as an<br />

attribute in the bean tag (XML context) or as a @Scope annotation if you are using annotation or Java configuration classes.<br />

48

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

Saved successfully!

Ooh no, something went wrong!