spring in action 学习笔记十四:用纯注解的方式实现spring mvc
在讲用纯注解的方式实现springmvc之前先介绍一个类:AbstractAnnotationDispatcherServletInitializer.这个类的作用是:任何一个类继承AbstractAnnotationDispatcherServletInitializer,将会自动的被用为配置DispatcherServlet,以及在DispatcherServlet中的的spring容器(如:spring-servlet.xml)文件。
spring in action的描述是:any class that extends AbstractAnnotationDispatcherServletInitializer will automatically be used to configure DispatcherServlet and the Spring Application context in the application's servlet context.
AbstractAnnotationDispatcherServlet的代码如下:
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.web.servlet.support; import org.springframework.util.ObjectUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; /**
* Base class for {@link org.springframework.web.WebApplicationInitializer}
* implementations that register a
* {@link org.springframework.web.servlet.DispatcherServlet DispatcherServlet}
* configured with annotated classes, e.g. Spring's
* {@link org.springframework.context.annotation.Configuration @Configuration} classes.
*
* <p>Concrete implementations are required to implement {@link #getRootConfigClasses()}
* and {@link #getServletConfigClasses()} as well as {@link #getServletMappings()}.
* Further template and customization methods are provided by
* {@link AbstractDispatcherServletInitializer}.
*
* <p>This is the preferred approach for applications that use Java-based
* Spring configuration.
*
* @author Arjen Poutsma
* @author Chris Beams
* @since 3.2
*/
public abstract class AbstractAnnotationConfigDispatcherServletInitializer
extends AbstractDispatcherServletInitializer { /**
* {@inheritDoc}
* <p>This implementation creates an {@link AnnotationConfigWebApplicationContext},
* providing it the annotated classes returned by {@link #getRootConfigClasses()}.
* Returns {@code null} if {@link #getRootConfigClasses()} returns {@code null}.
*/
@Override
protected WebApplicationContext createRootApplicationContext() {
Class<?>[] configClasses = getRootConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
rootAppContext.register(configClasses);
return rootAppContext;
}
else {
return null;
}
} /**
* {@inheritDoc}
* <p>This implementation creates an {@link AnnotationConfigWebApplicationContext},
* providing it the annotated classes returned by {@link #getServletConfigClasses()}.
*/
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext servletAppContext = new AnnotationConfigWebApplicationContext();
Class<?>[] configClasses = getServletConfigClasses();
if (!ObjectUtils.isEmpty(configClasses)) {
servletAppContext.register(configClasses);
}
return servletAppContext;
} /**
* Specify {@link org.springframework.context.annotation.Configuration @Configuration}
* and/or {@link org.springframework.stereotype.Component @Component} classes to be
* provided to the {@linkplain #createRootApplicationContext() root application context}.
* @return the configuration classes for the root application context, or {@code null}
* if creation and registration of a root context is not desired
*/
protected abstract Class<?>[] getRootConfigClasses(); /**
* Specify {@link org.springframework.context.annotation.Configuration @Configuration}
* and/or {@link org.springframework.stereotype.Component @Component} classes to be
* provided to the {@linkplain #createServletApplicationContext() dispatcher servlet
* application context}.
* @return the configuration classes for the dispatcher servlet application context or
* {@code null} if all configuration is specified through root config classes.
*/
protected abstract Class<?>[] getServletConfigClasses(); }
案例的目录结构如下图所示:

RootConfig的代码如下:
package spittr.config; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc; /**
* Created by ${秦林森} on 2017/6/12.
*/
@Configuration
/**
* excludeFilters是指明不被@ComponentScan扫描的类型
*/
@ComponentScan(basePackages = {"spittr"},excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = EnableWebMvc.class)}) public class RootConfig { }
WebConfig的代码如下:
package spittr.config; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import spittr.web.HomeController; /**
* Created by ${秦林森} on 2017/6/12.
*/
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"spittr.web"})
public class WebConfig extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//设置前缀
viewResolver.setPrefix("/WEB-INF/views/");
//设置后缀
viewResolver.setSuffix(".jsp");
viewResolver.setExposeContextBeansAsAttributes(true);
return viewResolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();//configure static content handling.
} }
package spittr.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /**
* Created by ${秦林森} on 2017/6/12.
*/
public class SpittrWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
} @Override
protected Class<?>[] getServletConfigClasses() {
//specifiy configuration class
return new Class<?>[]{WebConfig.class};
} @Override
protected String[] getServletMappings() {
return new String[]{"*.do"};//Map DispatcherServlet to
}
}
HomeController的代码如下:
package spittr.web; import org.springframework.stereotype.Controller;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; /**
* Created by ${秦林森} on 2017/6/12.
*/
@Controller
@RequestMapping(value = "/people")
public class HomeController {
@RequestMapping(value = "/home.do",method = RequestMethod.GET)
public String home(){
return "home";
}
}
home.jsp的代码如下:
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2017/6/12
Time: 16:25
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>spittr</title>
</head>
<body>
welcome to china ,one of the ancient civilized countries.
</body>
</html>
注意我这个项目的web应用名设置为该项目名。
启动tomcat 输入:http://localhost:8090/spring20170602/people/home.do
访问结果如下图所示:

spring in action 学习笔记十四:用纯注解的方式实现spring mvc的更多相关文章
- spring in action学习笔记十五:配置DispatcherServlet和ContextLoaderListener的几种方式。
在spring in action中论述了:DispatcherServlet和ContextLoaderListener的关系,简言之就是DispatcherServlet是用于加载web层的组件的 ...
- spring in action学习笔记十六:配置数据源的几种方式
第一种方式:JNDI的方式. 用xml配置的方式的代码如下: 1 <jee:jndi-lookup jndi-name="/jdbc/spittrDS" resource-r ...
- spring in action 学习笔记十:用@PropertySource避免注入外部属性的值硬代码化
@PropertySource的写法为:@PropertySource("classpath:某个.properties文件的类路径") 首先来看一下这个案例的目录结构,重点看带红 ...
- spring in action 学习笔记五:@Autowired这个注解如何理解
@Autowired这个注解的意思就是自动装配.他把一个bean对象自动装配到另一个对象中.下面的案例证明了spring的自动装配. 定义一个Sixi类.代码如下: package com.qls.a ...
- python3.4学习笔记(十四) 网络爬虫实例代码,抓取新浪爱彩双色球开奖数据实例
python3.4学习笔记(十四) 网络爬虫实例代码,抓取新浪爱彩双色球开奖数据实例 新浪爱彩双色球开奖数据URL:http://zst.aicai.com/ssq/openInfo/ 最终输出结果格 ...
- (C/C++学习笔记) 十四. 动态分配
十四. 动态分配 ● C语言实现动态数组 C语言实现动态数组,克服静态数组大小固定的缺陷 C语言中,数组长度必须在创建数组时指定,并且只能是一个常数,不能是变量.一旦定义了一个数组,系统将为它分配一个 ...
- spring in action 学习笔记九:如何证明在scope为prototype时每次创建的对象不同。
spring 中scope的值有四个:分别是:singleton.prototype.session.request.其中session和request是在web应用中的. 下面证明当scope为pr ...
- spring in action学习笔记一:DI(Dependency Injection)依赖注入之CI(Constructor Injection)构造器注入
一:这里先说一下DI(Dependency Injection)依赖注入有种表现形式:一种是CI(Constructor Injection)构造方法注入,另一种是SI(Set Injection) ...
- Spring in Action学习笔记(2)
Spring基础 AOP 面向切面编程 通知.连接点.切点.切面 Spring提供 4 种类型的AOP支持: 基于代理的经典SpringAOP:使用ProxyFactoryBean. 纯POJO切面: ...
随机推荐
- linux C 数组与指针
linux C 数组与指针 一.数组 数组是同一数据类型的一组值:属于引用类型,因此数组存放在堆内存中:数组元素初始化或给数组元素赋值都可以在声明数组时或在程序的后面阶段进行. 定义一维数组的一般格式 ...
- [BZOJ2243][SDOI2011]染色(树链剖分)
[传送门] 树链剖分就行了,注意线段树上颜色的合并 Code #include <cstdio> #include <algorithm> #define N 100010 # ...
- 笔记-python-functool-@wraps
笔记-python-functool-@wraps 1. wraps 经常看到@wraps装饰器,查阅文档学习一下 在了解它之前,先了解一下partial和updata_wrapper这两个 ...
- 3,Linux入门
操作系统的分类 Windows系列操作系统,Unix类操作系统,Linux类操作系统,Mac操作系统 提问:为什么要去学习Linux? 同学甲可能要问,超哥你介绍了这么多有关Linux的知识,但我还是 ...
- android MotionEvent
getAction() 获取事件的类型,这是一个组合值,由pointer的index值和事件类型值组合而成的 getActionMasked() 获取事件的类型,不具有其他信息 参考: http:// ...
- redis系列文章目录
redis系列文章目录 使用spring-data-redis实现incr自增 Redis 利用Hash存储节约内存 Redis学习笔记(九)redis实现时时直播列表缓存,支持分页[热点数据存储] ...
- UIView和CALayer是什么关系?
UIView显示在屏幕上归功于CALayer,通过调用drawRect方法来渲染自身的内容,调节CALayer属性可以调整UIView的外观,UIView继承自UIResponder,比起CALaye ...
- Visual Studio 2017 的 JavaScript 调试功能的关闭
关闭方法其实很简单,Options => Debugging => General => Enable JavaScript debugging for ASP.NET (Chrom ...
- 从事IT业一个8年老兵转行前的自我总结1——初爻
现在,本人已离开这个呆了8年的软件行业了.回想自己从半路出家,从实施开始做起,最终在一家外企做项目经理PM结束了自己的软件职业生涯.从一张白纸的自学开始,做过项目实施,客户培训,拿过需求,开发,架构设 ...
- 《算法》C++代码 Floyd
今天写写最短路径的Floyd算法(有翻译叫弗洛伊德,不过这奇葩翻译用来读读就好……). 这个算法的实质,广义来讲,其实是DP(动态规划).其实按说,算法应该先说说什么贪心.搜索.DP.二分之类的基本算 ...