springboot情操陶冶-web配置(二)

 承接前文springboot情操陶冶-web配置(一),本文将在前文的基础上分析下mvc的相关应用

MVC简单例子

直接编写一个Controller层的代码,返回格式为json

package com.example.demo.web.controller;  import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;  import java.util.HashMap; import java.util.Map;  /**  * @author nanco  * -------------  * -------------  * @create 2018/9/4  **/ @Controller @RequestMapping("/boot") @ResponseBody public class DemoController {      @RequestMapping(value = "/hello", method = RequestMethod.GET)     public Map<String, String> helloWorld() {         Map<String, String> result = new HashMap<>();         result.put("springboot", "hello world");         return result;     } }

运行之后,客户端工具HTTP访问链接http://127.0.0.1:9001/demoWeb/boot/hello便可得到以下的简单结果

{"springboot":"hello world"}

源码剖析

我们都知道springmvc最核心的组件便是DispatcherServlet,其本质是个Servlet组件,也包含了处理前端请求的逻辑,具体的可参照SpringMVC源码情操陶冶-DispatcherServlet。本文则讲解Springboot创建DispatcherServlet以及MVC配置的过程

DispatcherServletAutoConfiguration

首先需要配置DispatcherServlet组件,分为几个步骤来看


No.1 脑头注解了解下

@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @Configuration @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass(DispatcherServlet.class) @AutoConfigureAfter(ServletWebServerFactoryAutoConfiguration.class) @EnableConfigurationProperties(ServerProperties.class) public class DispatcherServletAutoConfiguration { }

由以上的注解可得知,其需要在ServletWebServerFactoryAutoConfiguration类注入至bean工厂后方可继续,这就和前文关联起来了。


No.2 DispatcherServletConfiguration内部类

    @Configuration     @Conditional(DefaultDispatcherServletCondition.class)     @ConditionalOnClass(ServletRegistration.class)     @EnableConfigurationProperties(WebMvcProperties.class)     protected static class DispatcherServletConfiguration {         // 引入了spring.mvc为开头的配置         private final WebMvcProperties webMvcProperties;          private final ServerProperties serverProperties;          public DispatcherServletConfiguration(WebMvcProperties webMvcProperties,                 ServerProperties serverProperties) {             this.webMvcProperties = webMvcProperties;             this.serverProperties = serverProperties;         }          // 直接创建DispatcherServlet并注入至bean工厂         @Bean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)         public DispatcherServlet dispatcherServlet() {             DispatcherServlet dispatcherServlet = new DispatcherServlet();             
                        
关键字:
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信