02 | @Scope 애너테이션 사용하기
스프링 프레임워크는 컨테이너를 설정하는 여러 가지 방법(XML, 애너테이션, 자바 설정 클래스, 새로운 GroovyBeanDefinitionReader)을 제공한다는 점을 기억해야 한다. 빈의 인스턴스를 얻는 데 애너테이션 기반 빈 또는 자바 빈 설정을 사용하는 경우에는 반드시 @Scope 애너테이션을 사용해야 한다. 예제 4-4는 수정된 코드를 보여준다.
예제 4-4 AnnotatedSearchEngine.java
package com.apress.isf.spring.annotated.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.apress.isf.java.model.Document;
import com.apress.isf.java.model.Type;
import com.apress.isf.java.service.SearchEngine;
import com.apress.isf.spring.data.DocumentDAO;
import com.apress.isf.spring.service.SearchEngineService;
@Service("engine")
@Scope("prototype")
public class AnnotatedSearchEngine implements SearchEngine {
private static final Logger log =
LoggerFactory.getLogger(SearchEngineService.class);
@Autowired
private DocumentDAO documentDAO;
public AnnotatedSearchEngine() {
if (log.isDebugEnabled())
log.debug("AnnotatedSearchEngine created: " + this);
}
public List<Document> findByType(Type documentType) {
List<Document> result = new ArrayList<Document>();
for (Document doc : listAll()) {
if (doc.getType().getName().equals(documentType.getName()))
result.add(doc);
}
return result;
}
public List<Document> listAll() {
return Arrays.asList(documentDAO.getAll());
}
}
예제 4-4는 "prototype" 값으로 클래스에 붙인 @Scope 애너테이션을 보여준다. 또한, Logger를 사용하고 있음을 볼 수 있다.