Friday, January 18, 2013

Spring 3.2 Java Configuration For SpringMvc

 @Configuration  
 @EnableWebMvc  
 @Import({DbConfig.class, LoggingConfig.class})  
 @ComponentScan(basePackages = {"org....", "org...."})  
 public class WebConfig extends WebMvcConfigurerAdapter {    
   @Bean  
   public ViewResolver viewResolver() {  
     InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
     resolver.setPrefix("WEB-INF/views/");  
     resolver.setSuffix(".jsp");  
     return resolver;  
   }  
   @Override  
   public void addResourceHandlers(ResourceHandlerRegistry registry) {  
     registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");  
   }  
 }  

The new @EnableWebMvc : The functionality of the annotation is equivalent to the XML version:
<mvc:annotation-driven />


 @RunWith(SpringJUnit4ClassRunner.class)  
 //defaults to "file:src/main/webapp"  
 @WebAppConfiguration  
 //detects "${classname}-context.xml" in same package or static nested @Configuration  
 //The default loader is AnnotationConfigWebContextLoader.class  
 @Configuration class  
 @ContextConfiguration(classes=WebConfig.class)  
 @Category(IntegrationTest.class)  
 public class WebIntegrationTest {  
   @Autowired  
   protected WebApplicationContext webApplicationContext;  
   protected MockMvc mockMvc;  
   @Before  
   public void setUp() {  
     mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();  
   }  
   @Test  
   public final void whenSpringContextIsInstantiated_thenNoExceptions(){  
   }  
 }  

2 comments: