更多spring相关博文参考: spring.hhui.top

前一篇博文讲了SpringMVC+web.xml的方式创建web应用,用过SpringBoot的童鞋都知道,早就没有xml什么事情了,其实Spring 3+, Servlet 3+的版本,就已经支持java config,不用再写xml;本篇将介绍下,如何利用java config取代xml配置

本篇博文,建议和上一篇对比看,贴出上一篇地址

  • 190316-Spring MVC之基于xml配置的web应用构建

I. Web构建

1. 项目依赖

对于依赖这一块,和前面一样,不同的在于java config 取代 xml

<artifactId>200-mvc-annotation</artifactId>
<packaging>war</packaging><properties><spring.version>5.1.5.RELEASE</spring.version>
</properties><dependencies><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.eclipse.jetty.aggregate</groupId><artifactId>jetty-all</artifactId><version>9.2.19.v20160908</version></dependency>
</dependencies><build><finalName>web-mvc</finalName><plugins><plugin><groupId>org.eclipse.jetty</groupId><artifactId>jetty-maven-plugin</artifactId><version>9.4.12.RC2</version><configuration><httpConnector><port>8080</port></httpConnector></configuration></plugin></plugins>
</build>
复制代码

细心的童鞋会看到,依赖中多了一个jetty-all,后面测试篇幅会说到用法

2. 项目结构

第二节依然放上项目结构,在这里把xml的结构也截进来了,对于我们的示例demo而言,最大的区别就是没有了webapp,更没有webapp下面的几个xml配置文件

3. 配置设定

现在没有了配置文件,我们的配置还是得有,不然web容器(如tomcat)怎么找到DispatchServlet呢

a. DispatchServlet 声明

同样我们需要干的第一件事情及时声明DispatchServlet,并设置它的应用上下文;可以怎么用呢?从官方找到教程

{% blockquote @SpringWebMvc教程 docs.spring.io/spring/docs… %}

The DispatcherServlet, as any Servlet, needs to be declared and mapped according to the Servlet specification by using Java configuration or in web.xml. In turn, the DispatcherServlet uses Spring configuration to discover the delegate components it needs for request mapping, view resolution, exception handling

{% endblockquote %}

上面的解释,就是说下面的代码和web.xml的效果是一样一样的

public class MyWebApplicationInitializer implements WebApplicationInitializer {@Overridepublic void onStartup(ServletContext servletCxt) {// Load Spring web application configurationAnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();ac.register(AppConfig.class);ac.refresh();// Create and register the DispatcherServletDispatcherServlet servlet = new DispatcherServlet(ac);ServletRegistration.Dynamic registration = servletCxt.addServlet("mvc-dispatcher", servlet);registration.setLoadOnStartup(1);registration.addMapping("/*");}
}
复制代码

当然直接实现接口的方式有点粗暴,但是好理解,上面的代码和我们前面的web.xml效果一样,创建了一个DispatchServlet, 并且绑定了url命中规则;设置了应用上下文AnnotationConfigWebApplicationContext

这个上下文,和我们前面的配置文件mvc-dispatcher-servlet有点像了;如果有兴趣看到项目源码的同学,会发现用的不是上面这个方式,而是及基础接口AbstractDispatcherServletInitializer

public class MyWebApplicationInitializer extends AbstractDispatcherServletInitializer {@Overrideprotected WebApplicationContext createRootApplicationContext() {return null;}@Overrideprotected WebApplicationContext createServletApplicationContext() {AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();//        applicationContext.setConfigLocation("com.git.hui.spring");applicationContext.register(RootConfig.class);applicationContext.register(WebConfig.class);return applicationContext;}@Overrideprotected String[] getServletMappings() {return new String[]{"/*"};}@Overrideprotected Filter[] getServletFilters() {return new Filter[]{new HiddenHttpMethodFilter(), new CharacterEncodingFilter()};}
}
复制代码

看到上面这段代码,这个感觉就和xml的方式更像了,比如Servlet应用上下文和根应用上下文

说明

上面代码中增加的Filter先无视,后续会有专文讲什么是Filter以及Filter可以怎么用

b. java config

前面定义了DispatchServlet,接下来对比web.xml就是需要配置扫描并注册bean了,本文基于JavaConfig的方式,则主要是借助 @Configuration 注解来声明配置类(这个可以等同于一个xml文件)

前面的代码也可以看到,上下文中注册了两个Config类

RootConfig定义如下,注意下注解@ComponentScan,这个等同于<context:component-sca/>,指定了扫描并注册激活的bean的包路径

@Configuration
@ComponentScan(value = "com.git.hui.spring")
public class RootConfig {
}
复制代码

另外一个WebConfig的作用则主要在于开启WebMVC

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
}
复制代码

4. 实例代码

实例和上一篇一样,一个普通的Server Bean和一个Controller

@Component
public class PrintServer {public void print() {System.out.println(System.currentTimeMillis());}
}
复制代码

一个提供rest服务的HelloRest

@RestController
public class HelloRest {@Autowiredprivate PrintServer printServer;@GetMapping(path = "hello", produces="text/html;charset=UTF-8")public String sayHello(HttpServletRequest request) {printServer.print();return "hello, " + request.getParameter("name");}@GetMapping({"/", ""})public String index() {return UUID.randomUUID().toString();}
}
复制代码

5. 测试

测试依然可以和前面一样,使用jetty来启动,此外,介绍另外一种测试方式,也是jetty,但是不同的是我们直接写main方法来启动服务

public class SpringApplication {public static void main(String[] args) throws Exception {Server server = new Server(8080);ServletContextHandler handler = new ServletContextHandler();// 服务器根目录,类似于tomcat部署的项目。 完整的访问路径为ip:port/contextPath/realRequestMapping//ip:port/项目路径/api请求路径handler.setContextPath("/");AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();applicationContext.register(WebConfig.class);applicationContext.register(RootConfig.class);//相当于web.xml中配置的ContextLoaderListenerhandler.addEventListener(new ContextLoaderListener(applicationContext));//springmvc拦截规则 相当于web.xml中配置的DispatcherServlethandler.addServlet(new ServletHolder(new DispatcherServlet(applicationContext)), "/*");server.setHandler(handler);server.start();server.join();}
}
复制代码

测试示意图如下

6. 小结

简单对比下xml的方式,会发现java config方式会清爽很多,不需要多个xml配置文件,维持几个配置类,加几个注解即可;当然再后面的SpringBoot就更简单了,几个注解了事,连上面的两个Config文件, ServletConfig都可以省略掉

另外一个需要注意的点就是java config的运行方式,在servlet3之后才支持的,也就是说如果用比较老的jetty是起不来的(或者无法正常访问web服务)

II. 其他

- 系列博文

web系列:

  • Spring Web系列博文汇总

mvc应用搭建篇:

  • 190316-Spring MVC之基于xml配置的web应用构建
  • 190317-Spring MVC之基于java config无xml配置的web应用构建

0. 项目

  • 工程:spring-boot-demo
  • 项目: github.com/liuyueyi/sp…

1. 一灰灰Blog

  • 一灰灰Blog个人博客 blog.hhui.top
  • 一灰灰Blog-Spring专题博客 spring.hhui.top

一灰灰的个人博客,记录所有学习和工作中的博文,欢迎大家前去逛逛

2. 声明

尽信书则不如,以上内容,纯属一家之言,因个人能力有限,难免有疏漏和错误之处,如发现bug或者有更好的建议,欢迎批评指正,不吝感激

  • 微博地址: 小灰灰Blog
  • QQ: 一灰灰/3302797840

3. 扫描关注

一灰灰blog

知识星球

Spring MVC之基于java config无xml配置的web应用构建相关推荐

  1. Spring MVC之基于xml配置的web应用构建

    2019独角兽企业重金招聘Python工程师标准>>> 更多spring博文参考: http://spring.hhui.top/ 直接用SpringBoot构建web应用可以说非常 ...

  2. Spring+Spring Mvc+Mybatis+MySqlite(SSM框架整合Xml配置)

    MyBatis Spring-mvc的对应配置 Log的配置 MyBatis 我们在resources下创建spring-mybatis.xml,对应的参数配置 <?xml version=&q ...

  3. Spring MVC 无XML配置入门示例

    Spring MVC 无XML(纯 Java)配置入门示例 本示例是从<Spring in Action, Fourth Edition>一书而来,涉及的是书中5.1节部分内容,书中其实说 ...

  4. 零配置 之Spring基于Java类定义Bean配置元数据

    转载自  [第十二章]零配置 之 12.4 基于Java类定义Bean配置元数据 --跟我学spring3 12.4  基于Java类定义Bean配置元数据 12.4.1  概述 基于Java类定义B ...

  5. Spring MVC的DispatcherServlet – Java开发人员应该知道的10件事

    如果您使用过Spring MVC,那么您应该知道什么是DispatcherServlet? 它实际上是Spring MVC的心脏,确切地说是MVC设计模式或控制器的C语言. 应该由Spring MVC ...

  6. 视频教程-基础篇:Spring MVC快速开发-Java

    基础篇:Spring MVC快速开发 毕业于清华大学软件学院软件工程专业,曾在Accenture.IBM等知名外企任管理及架构职位,近15年的JavaEE经验,近8年的Spring经验,一直致力于架构 ...

  7. python相关毕设题目_基于java的一个有创意的web毕设题目

    基于java的一个有创意的web毕设题目 一个有创意的web毕设题目 本课题将结合基于Java Web技术的名师一对一课程预约系统,根据本课题的最终目标,在线用户注册.相关信息发布.在线咨询.预约试听 ...

  8. Spring MVC的WebMvcConfigurerAdapter用法收集(零配置,无XML配置)

    原理先不了解,只记录常用方法 用法: @EnableWebMvc 开启MVC配置,相当于 <?xml version="1.0" encoding="UTF-8&q ...

  9. Spring:使基于Java的配置更加优雅

    大家好,我很久没有写新文章了. 积累了很多资料,需要在不久的将来在我的博客中发布. 但是现在我想谈谈Spring MVC应用程序配置. 确切地说,我想谈谈基于Java的Spring配置. 尽管在3.0 ...

最新文章

  1. 数据库设计和管理规范
  2. Android.bp 语法浅析-Android10.0编译系统(八)
  3. 二叉树(BST)之创建二叉搜索树
  4. ibatis多参数的问题
  5. Vue 动态创建实例
  6. RHEL6 下Cfengine V3 安装测试1
  7. 1.3tf的varible\labelencoder
  8. 摘抄一篇:图的存储结构
  9. 三种分布式锁 简易说说(包含前一篇提到的redis分布式锁)
  10. [转]Oracle销售人员普遍腐败?
  11. 汇编64位无法生成可用exe_MASM学习x86汇编语言2 寄存器、伪指令与程序调试
  12. yum文件,来自网络
  13. 【通信】基于matlab GUI短波通信系统仿真【含Matlab源码 647期】
  14. Thinkpad x230 win7/xp 双系统安装全过程
  15. 利用STM32PWM占空比实现呼吸灯
  16. erp系统软件的三层定义
  17. 吴恩达老师深度学习课程完整笔记
  18. 给未来的电子工程师nbsp;---电子牛人给…
  19. glog logging library for C++
  20. 软件安全学习笔记——C语言

热门文章

  1. phpstorm统计程序行数_Python 实现代码行数统计
  2. C++新特性探究(13.6):右值引用再探究
  3. python画相关性可视化图_Python可视化matplotlibseborn16-相关性热图
  4. select 存储过程 mysql_MySQL存储过程无法使用SELECT(基本问题)
  5. python中if和elif的区别_浅谈对python中if、elif、else的误解
  6. linux 挂载raid_linux初学者-磁盘阵列篇
  7. 爬取亚马逊评论_如何利用插件抓取亚马逊评论和关键词?
  8. python执行变量次_当脚本再次执行时需要一个变量来保留它的值(Python)
  9. WSGI Server/Gateway
  10. AudioBuffer