예제 3-13에서는 클래스 상단에 @Configuration을 추가하고, 메서드에 @Bean 애너테이션을 추가하고 있다. @Configuration을 사용하면 스프링 컨테이너에 “여기에 빈들의 정의가 있다”고 알리는 것과 같다. 그리고 메서드에 @Bean 애너테이션을 사용할 때는 <bean /> 태그를 생성하고 프로퍼티를 설정하는 것과 같다. 따라서 이 클래스는 사용할 빈들이 무엇이며 빈들이 어떻게 연관되어 있는지를 스프링 컨테이너에 알린다.
이제 유닛 테스트에서 이 새로운 자바 빈 설정 기능을 사용해보자(예제 3-14 참고).
예제 3-14 MyDocumentsBeanConfigurationTest.java
package com.apress.isf.spring.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
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.config.MyDocumentsContext;
public class MyDocumentsBeanConfigurationTest {
private ApplicationContext context;
private SearchEngine engine;
private Type webType;
@Before
public void setup() {
context = new AnnotationConfigApplicationContext(MyDocumentsContext.class);
engine = context.getBean(SearchEngine.class);
webType = context.getBean(Type.class);
}
@Test
public void testWithBeanConfigurationFindByType() {
List<Document> documents = engine.findByType(webType);
assertNotNull(documents);
assertTrue(documents.size() == 1);
assertEquals(webType.getName(), documents.get(0).getType().getName());
assertEquals(webType.getDesc(), documents.get(0).getType().getDesc());
assertEquals(webType.getExtension(),
documents.get(0).getType().getExtension());
}
@Test
public void testWithBeanConfigurationListAll() {
List<Document> documents = engine.listAll();
assertNotNull(documents);
assertTrue(documents.size() == 4);
}
}