1.之前搭建Spring MVC 框架通常都使用配置文件的方式進行,相對比較繁瑣。spring 提供了使用註解方式搭建Spring MVC 框架的方式,方便簡潔。使用Spring IOC 做爲根容器管理service、dao、datasource,使用spring MVC 容器做爲子容器管理controller、視圖解析器java
spring 官方文檔中有相關示例web
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 執行攔截路徑。spring
2.首先建立一個Maven 工程,packaging 爲war類型,並在插件中指定忽略web.xml,不然會報錯apache
<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 之外的組件mvc
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 默認的掃描規則,不然會掃描到全部的組件。這樣這個容器的就造成了一種互補關係。app
@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,啓動並測試jsp
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 配置文件中配置組件的方法。maven
@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { // Implement configuration methods... }
8.直接在spring MVC 容器的配置相似,實現以上功能,並配視圖解析器,靜態資源攔截,添加攔截器等。WebMvcConfigurerAdapter 這個抽象類實現了 WebMvcConfigurer ,咱們直接繼承它,從而避免去挨個實現 WebMvcConfigurer 裏面全部的方法ide
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 註解版搭建,其他的功能組件能夠在經過編寫配置類的方式進行註冊。