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

Table 4-1. Bean Scopes<br />

Scope<br />

singleton<br />

prototype<br />

request<br />

session<br />

globalSession<br />

Definition<br />

The <strong>Spring</strong> container returns a single instance. This is the default value.<br />

The <strong>Spring</strong> container returns a new instance every time it is requested.<br />

The <strong>Spring</strong> container returns a new instance on each HTTP request; this is used in a web context.<br />

The <strong>Spring</strong> container returns a new instance on each HTTP session; this is used in a web context.<br />

The <strong>Spring</strong> container returns a single instance per global HTTP session; this is used in a<br />

web context.<br />

In the next sections, you will see different ways to use these bean scopes. You need to be very careful to choose<br />

the right scope because that could impact your application.<br />

Using the @Scope Annotation<br />

You need to remember that the <strong>Spring</strong> <strong>Framework</strong> has different ways to configure its container: XML, annotations,<br />

Java configuration classes, and the new GroovyBeanDefinitionReader. If you are going to use either the annotated<br />

beans or the Java bean configuration to get the instance of your beans, then it is necessary to use the @Scope<br />

annotation. Listing 4-4 shows the modified code.<br />

Listing 4-4. AnnotatedSearchEngine.java<br />

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

import java.util.ArrayList;<br />

import java.util.Arrays;<br />

import java.util.List;<br />

import org.slf4j.Logger;<br />

import org.slf4j.LoggerFactory;<br />

import org.springframework.beans.factory.annotation.Autowired;<br />

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

import org.springframework.stereotype.Service;<br />

import com.apress.isf.java.model.Document;<br />

import com.apress.isf.java.model.Type;<br />

import com.apress.isf.java.service.SearchEngine;<br />

import com.apress.isf.spring.data.DocumentDAO;<br />

import com.apress.isf.spring.service.ServiceSearchEngine;<br />

@Service("engine")<br />

@Scope("prototype")<br />

public class AnnotatedSearchEngine implements SearchEngine {<br />

private static final Logger log =<br />

LoggerFactory.getLogger(ServiceSearchEngine.class);<br />

49

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

Saved successfully!

Ooh no, something went wrong!