使用JavaConfig配置SpringMVC

目录结构

使用JavaConfig配置SpringMVC_第1张图片

web.xml:



    
    
        contextClass
        
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        
    

    
    
        contextConfigLocation
        springdemo.config.AppConfig
    

    
    
        org.springframework.web.context.ContextLoaderListener
    

    
    
        dispatcher
        org.springframework.web.servlet.DispatcherServlet
        
        
            contextClass
            
                org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            
        
        
        
            contextConfigLocation
            springdemo.config.MvcConfig
        
    

    
    
        dispatcher
        /
    

SpringMVC配置类:

@EnableWebMvc
@Configuration
@ComponentScan(basePackages={"springdemo.controller"})
public class MvcConfig {
    
    /**
     * 配置JSP视图解析器
     * @return
     */
    @Bean
    public ViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }
    
    /**
     * 配置默认的Servlet来处理静态资源
     * @return
     */
    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        return new WebMvcConfigurerAdapter() {
            @Override
            public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
                configurer.enable();
            }
        };
    }
}

Controller:

@Controller
public class CoffeeController {
    @RequestMapping(value="/show",method=RequestMethod.GET)
    public String showCoffee(){
        return "coffee";
    }
}

测试类:

@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes={MvcConfig.class})
public class CoffeeTest {
    private MockMvc mockMvc;
    
    @Autowired
    private WebApplicationContext wac;
    
    @Before
    public void init(){
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }
    
    @Test
    public void testShowCoffee() throws Exception{
        ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.get("/show"));
        resultActions.andExpect(MockMvcResultMatchers.view().name("coffee"));
    }
}

可以选择继承AbstractAnnotationConfigDispatcherServletInitializer来替换web.xml中的配置:

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{

    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[]{AppConfig.class};
    }

    @Override
    protected Class[] getServletConfigClasses() {
        return new Class[]{MvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

pom.xml :Spring pom.xml配置

你可能感兴趣的:(使用JavaConfig配置SpringMVC)