Spring-Context之三:使用XML和Groovy DSL配置Bean(二)

2014-11-24 01:25:27 · 作者: · 浏览: 1
vieService : movieService
}
这种更好理解了,ref方法也是可选的。
来照旧写个测试来测一下。
GroovyDSLConfigurationTest.java
package huangbowen.net;
import huangbowen.net.service.Cinema;
import huangbowen.net.service.DefaultMovieService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AbstractGenericContextLoader;
import static huangbowen.net.GroovyDSLConfigurationTest.*;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:Configuration.groovy", loader = GenericGroovyContextLoader.class)
public class GroovyDSLConfigurationTest {
public static class GenericGroovyContextLoader extends
AbstractGenericContextLoader {
@Override
protected BeanDefinitionReader createBeanDefinitionReader(
GenericApplicationContext context) {
return new GroovyBeanDefinitionReader(context);
}
@Override
protected String getResourceSuffix() {
return ".groovy";
}
}
@Autowired
private ApplicationContext applicationContext;
@Autowired
private Cinema cinema;
@Test
public void shouldGetCinemaInstance() {
Cinema cinema = applicationContext.getBean(Cinema.class);
assertNotNull(cinema);
}
@Test
public void shouldGetAutowiredCinema() {
assertNotNull(cinema);
}
@Test
public void shouldGetMovieServiceInstance() {
assertNotNull(cinema.getMovieService());
assertThat(cinema.getMovieService(), instanceOf(DefaultMovieService.class));
}
}
在集成测试中如果加载xml配置文件,Spring提供了GenericXmlContextLoader类,如果加载注解方式的配置类,Spring提供了AnnotationConfigContextLoader类。但是对于Groovy配置文件Spring testContext框架还未提供相应的Loader,所以在本测试方法中需要自己实现一个Loader,其实也简单,只要实现两个方法即可。