Spring Boot 学习之路——1 入门demo

前言:

使用Spring Boot已有一年多时间,却从未静下心来总结,今天抽空写个傻瓜式教程,巩固一下。

Spring Boot的主要优点:
  • 为所有Spring开发者更快的入门
  • 开箱即用,提供各种默认配置来简化项目配置
  • 内嵌式容器简化Web项目
  • 没有冗余代码生成和XML配置的要求(Spring 4可实现零配置)


入门demo很简单,实现一个简单的Http 请求处理。废话不说看截图。

  • IDE : IntelliJ IDEA 2018.1 x64
  • JDK : 1.8
  • Spring Framework 5.0.5

1.创建项目

Spring Boot 学习之路——1 入门demo


Spring Boot 学习之路——1 入门demo


Spring Boot 学习之路——1 入门demo

创建完毕,项目结构如下:

Spring Boot 学习之路——1 入门demo


2 添加Controller 

controller代码如下:

package com.joanna.springbootdemo.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/sayHello")
public class SayHello {

    @RequestMapping(value = "/humanSays", method = RequestMethod.GET)
    public String humanSays(@RequestParam(name = "name", required = false) String name,
                            @RequestParam(name = "comeFrom", required = false) String comeFrom) {
        return "Hello " + name + ", who comes from " + comeFrom + ", I'm a human";
    }

    @RequestMapping(value = "/catSays", method = RequestMethod.GET)
    public String catSays(@RequestParam(name = "name", required = false) String name) {
        return "Hello " + name + ", I'm a cat";
    }

    @RequestMapping(value = "/dogSays", method = RequestMethod.GET)
    public String dogSays(@RequestParam(name = "name", required = false) String name) {
        return "Hello " + name + ", I'm a dog";
    }

}

添加pom依赖如下(idea自动add dependency,棒棒哒):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

3 启动

启动方式:

  1. Application类main方法启动
  2. mvn clean install/package cd 到target目录,java -jar 项目.jar,注意这里需要加入依赖spring-boot-maven-plugin生成可执行的jar
  3. mvn spring-boot: run 启动

启动后,打开浏览器中访问:http://localhost:8080/sayHello/humanSays?name=Joanna&comeFrom=China   

可以看到页面输出:Hello Joanna, who comes from China, I'm a human


打完收工。