SpringBoot demo初始

时间:2023-02-21 07:59:35


SpringBoot 初始

需求描述

通过spring boot搭建并配置简单的服务实例,通过访问http://localhost:8080/index显示


{"上海":"一线城市","合肥":"二线城市"}


解决方法

下载模板

Step1:从springboot官网下载模板,当前选择是maven工程、Java 8、WAR方式、Springboot 版本为2.6.2,详见下图:

​https://start.spring.io/​

SpringBoot demo初始

 导入工程

Step2:在IntelliJ IDEA里导入已存在项目,详见下图:

SpringBoot demo初始

 编写控制类

Step3:com.demo下新建包controller并在其下建立IndexController类,类代码见下:

package com.demo.controller;

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class IndexController {
@RequestMapping("/index")
public Map <String,String> index() {
Map map = new HashMap<String, String>();
map.put("合肥","二线城市");
map.put("上海","一线城市");
return map;
}


}

配置应用类

Step4:在DemoApplication类里配置注解@ComponentScan(要扫描的包),详见如下代码:

package com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan(basePackages = {"com.demo.controller"})
public class DemoApplication {

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

}

启动服务

Step5:启动服务(右键Step4里的DemoApplication类运行),访问服务(​​http://localhost:8080/index​​)

SpringBoot demo初始