SpringBoot框架(3):创建SpringBoot项目

  • 打开网址:http://start.spring.io/
    填写group和artifact等信息,并选择一个依赖web,单击生成项目,解压文件,使用ecplise导入maven项目。
    image.png

查看目录结构,发现会生成一个类,此类就是启动项目的类,里面有一个main方法,不用tomcat部署项目,直接启动运行。



代码如下:接着定义一个Controller类,使用restController注解,

package cn.springboot.test.controller;
 
import java.util.HashMap;
import java.util.Map;
 
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
//该注解等价于@Controller+@ResponseBody的结合,使用这个注解的类里面的方法都以json格式输出。
public class HelloController {
  private static Map userMap = new HashMap();
  private void initUserMap(){
      userMap.put(1, "张三");userMap.put(2, "李四");
      userMap.put(3, "王五");userMap.put(4, "赵二");
  }
    
  @RequestMapping("/hello/{id}")
  public String findById(@PathVariable Integer id) {
      initUserMap();
      return "你好,用户:" + userMap.get(id);
  }
}

当路径为"http://localhost:8080/hello/1"时,浏览器结果为:

SpringBoot启动有三种方式:

  1. main方法启动
  2. 使用maven命令 mvn spring-boot:run 在命令行启动该应用
  3. Java -jar 命令启动,需要先运行“mvn package”进行打包

你可能感兴趣的:(SpringBoot框架(3):创建SpringBoot项目)