1.以前搭建Spring MVC 框架一般都使用配置文件的方式進行,相對比較繁瑣。spring 提供了使用注解方式搭建Spring MVC 框架的方式,方便簡潔。使用Spring IOC 作為根容器管理service、dao、datasource,使用spring MVC 容器作為子容器管理controller、視圖解析器
spring 官方文檔中有相關示例
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] { RootConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { App1Config.class }; } @Override protected String[] getServletMappings() { return new String[] { "/app1/*" }; } }
使用繼承 AbstractAnnotationConfigDispatcherServletInitializer 的方式創建啟動類,其中 getRootConfigClasses 指定父容器的配置類,相當於在web.xml 配置文件中配置監聽器加載spring的配置文件,getServletConfigClasses指定spring MVC 的配置文件,相當於在web.xml配置DispatcherServlet,getServletMappings 執行攔截路徑。
2.首先創建一個Maven 工程,packaging 為war類型,並在插件中指定忽略web.xml,否則會報錯
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.1.0</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build>
3.創建spring IOC 的配置類,管理除了Controller 以外的組件
package com.spring.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.stereotype.Controller; /** * spring 配置文件,構建父容器,掃描service、dao 等,但是controller交給spring mvc 來管理 * @author Administrator * */ @ComponentScan(value="com.spring",excludeFilters= { @Filter(type=FilterType.ANNOTATION,classes= {Controller.class}) }) public class SpringContextConfig { }
4.創建Spring MVC 配置類,管理Controller,注意此時需要關閉compentscan 默認的掃描規則,否則會掃描到所有的組件。這樣這個容器的就形成了一種互補關系。
@ComponentScan(value = "com.spring",includeFilters= { @Filter(type = FilterType.ANNOTATION,classes= {Controller.class}) },useDefaultFilters=false) public class AppConfig extends WebMvcConfigurerAdapter{ }
5.創建初始化類,指定兩個容器的配置類,並指定攔截路徑
package com.spring; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import com.spring.config.AppConfig; import com.spring.config.SpringContextConfig; public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { //獲取父容器的配置文件(spring IOC ,類似於spring 配置文件) @Override protected Class<?>[] getRootConfigClasses() { // TODO Auto-generated method stub return new Class<?>[] {SpringContextConfig.class}; } //獲取父容器的配置文件(springMVC IOC ,類似於spring MVC 配置文件,獲取DispatcherServlet) @Override protected Class<?>[] getServletConfigClasses() { // TODO Auto-generated method stub return new Class<?>[] {AppConfig.class}; } //獲取DispatcherServlet 的映射路徑 @Override protected String[] getServletMappings() { // TODO Auto-generated method stub return new String[]{"/"}; } }
6.編寫測試controller ,services,啟動並測試
package com.spring.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.spring.service.HelloService; @Controller public class HelloController { @Autowired HelloService helloService; @ResponseBody @RequestMapping("/hello") public String sayHello() { String sayHello = helloService.sayHello("World"); return sayHello; } }
7.之前采用配置文件的方式,我們可以需要在spring MVC 的配置文件中使用 <mvc:annotation-driven/> 去開始MVC 配置,並且配置如視圖解析器,攔截器等組件,在采用注解方式后同樣可以完成在配置文件中完成的東西,官方文檔中給出的示例,需要我們編寫一個配置類,然后開啟mvc注解,實現
WebMvcConfigurer 接口,這個接口定義了一系列方法對應 在spring MVC 配置文件中配置組件的方法。
@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { // Implement configuration methods... }
8.直接在spring MVC 容器的配置類似,實現以上功能,並配視圖解析器,靜態資源攔截,添加攔截器等。WebMvcConfigurerAdapter 這個抽象類實現了 WebMvcConfigurer ,我們直接繼承它,從而避免去挨個實現 WebMvcConfigurer 里面所有的方法
package com.spring.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.FilterType; import org.springframework.stereotype.Controller; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.spring.intercepter.MyIntercepter; /** * Spring mvc 配置文件,只掃描Controller * @author Administrator * */ @ComponentScan(value = "com.spring",includeFilters= { @Filter(type = FilterType.ANNOTATION,classes= {Controller.class}) },useDefaultFilters=false) @EnableWebMvc public class AppConfig extends WebMvcConfigurerAdapter{ @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/views/", ".jsp"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyIntercepter()).addPathPatterns("/**"); } }
下面是自定義的攔截器
package com.spring.intercepter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyIntercepter implements HandlerInterceptor{ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("----------目標方法執行前-------------"); return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("----------目標方法執行后-------------"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("----------頁面響應前-------------"); } }
測試controller 如下:
package com.spring.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.spring.service.HelloService; @Controller public class HelloController { @Autowired HelloService helloService; @ResponseBody @RequestMapping("/hello") public String sayHello() { String sayHello = helloService.sayHello("World"); return sayHello; } @RequestMapping("/helloworld") public String helloWorld() { return "hello"; } }
測試結果如下,成功跳轉到jsp,並且顯示了圖片,攔截器也做了相應的輸出
至此基本完成Spring MVC 注解版搭建,其余的功能組件可以在通過編寫配置類的方式進行注冊。