• Spring Boot 学习(一) 快速搭建SpringBoot 项目


    快速搭建一个 Spring Boot 项目

    部分参考于《深入实践Spring Boot》、《Spring实战 第四版》与程序猿DD的有关博客。

    参考(嘟嘟独立博客):http://tengj.top/2017/02/26/springboot1/

    搭建项目:

    创建Spring Boot操作步骤如下:
    1.在File菜单里面选择 New > Project,然后选择Spring Initializr,接着如下图一步步操作即可。

    项目结构

    根据上面的操作已经初始化了一个Spring Boot的框架了,项目结构如下:

    如你所见,项目里面基本没有代码,除了几个空目录外,还包含如下几样东西。

      • pom.xml:Maven构建说明文件。
      • Chapter1Application.java:一个带有main()方法的类,用于启动应用程序(关键)。
      • Chapter1ApplicationTests.java:一个空的Junit测试类,它加载了一个使用Spring Boot字典配置功能的Spring应用程序上下文。
      • application.properties:一个空的properties文件,你可以根据需要添加配置属性。

    ------------------------------------------------------------------------------------------分割线------------------------------------------------------------------------------------------------------------------

    Spring Boot 优点

    1. 轻量化
    2. 提供 Spring 框架各种默认配置来简化项目配置
    3. 内嵌 Web 容器
    4. 没有冗余代码生成和XML配置要求

    Maven 导包

    • spring-boot-starter:核心模块,包括了自动配置支持、日志和YAML
    • spring-boot-starter-test:测试模块,包括JUnit、Hamcrest、Mockito
    • spring-boot-starter-web:Web模块

    开工

    一个 Spring Boot 案例应该包括四个部分(主加载类、逻辑实现类、单元测试类、以及资源配置文件)。

    1. 资源配置文件:这个文件主要记录了框架下各种设置;前面,我们提到过 Spring Boot 提供 Spring 的默认设置,所以一开始并不需要对这个文件做任何修改,让框架内嵌的Web容器加载该文件即可。* 注意:命名为application.properties *,并且默认端口为8080。

    2. 主加载类:Spring Boot 框架下,最重要的一个类,也是启动整个框架的入口。一般有两种代码模板,好像也没有什么区别。这里先写一种:

    @SpringBootApplication 
    
    public class Application {
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

     3. 逻辑实现类:就是我们提供的服务接口,一般就是我们的Controller层。这里实现一个简单的”hello world!”的Controller,便于测试。 启动项目后,访问 http://localhost:8080/hello 来访问这个控制器。

    @RestController
    public class HelloController {
    
        @RequestMapping("/hello")
        public String index(){
            return "hello world!";
        }
    }
    

    4. 单元测试类:顾名思义,就是一个用来测试我们的逻辑实现类的类。

    这里使用 JUnit 模拟一个 http 请求来测试我们的 HelloController。

    同时,这里涉及到Spring AOP@Before,有兴趣的也可以去查看一下。

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = MockServletContext.class)
    @WebAppConfiguration  
    //测试环境使用,用来表示测试环境使用的ApplicationContext将是WebApplicationContext类型的
    public class ApplicationTest  {
    
        private MockMvc mvc;
    
        @Before
        public void setUp() throws Exception{
            //通过MockMvcBuilders.xxxSetup().build()创建一个MockMvc进行测试;
            mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
        }
    
        @Test
        public void getHello() throws Exception{
            mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                    .andExpect(status().isOk())
                    .andExpect(content().string(equalTo("hello world!")))
                    .andDo(MockMvcResultHandlers.print())
                    .andReturn();
        }
        /**
         * 1、mockMvc.perform执行一个请求。
         * 2、MockMvcRequestBuilders.get("XXX")构造一个请求。
         * 3、ResultActions.andExpect添加执行完成后的断言。
         * 4、ResultActions.andDo添加一个结果处理器,表示要对结果做点什么事情
         *   比如此处使用MockMvcResultHandlers.print()输出整个响应结果信息。
         * 5、ResultActions.andReturn表示执行完成后返回相应的结果。
         */
    }
    

     最后附上, http 请求响应后的报文。

    MockHttpServletRequest:
          HTTP Method = GET
          Request URI = /hello
           Parameters = {}
              Headers = {Accept=[application/json]}
    
    Handler:
                 Type = qg.fangrui.boot.web.HelloController
               Method = public java.lang.String qg.fangrui.boot.web.HelloController.index()
    
    Async:
        Async started = false
         Async result = null
    
    Resolved Exception:
                 Type = null
    
    ModelAndView:
            View name = null
                 View = null
                Model = null
    
    FlashMap:
           Attributes = null
    
    MockHttpServletResponse:
               Status = 200
        Error message = null
              Headers = {Content-Type=[application/json;charset=ISO-8859-1], Content-Length=[12]}
         Content type = application/json;charset=ISO-8859-1
                 Body = hello world!
        Forwarded URL = null
       Redirected URL = null
              Cookies = []
    
  • 相关阅读:
    可变参数模板的递归解析
    在Ubuntu上安装多个版本的g++ 并进行默认版本切换
    不错的威盾PHP加密专家解密算法
    文章相关性分析详细介绍
    c#连接mysql中文乱码解决方案(MySql.Data.dll)
    firefox用12306Helper 0.2结合ie tab+自动订火车票和完成支付全攻略
    Nutch命令大全
    Jtable利用SetModel进行数据绑定
    在php中使用CKEDITOR在线编辑器
    Nutch1.2搜索引擎使用详解
  • 原文地址:https://www.cnblogs.com/MaxElephant/p/8108224.html
Copyright © 2020-2023  润新知