SpringBoot入门
文章目录
1. 初识SpringBoot
SpringBoot官网:https://spring.io/projects/spring-boot/
我们可以了解到,SpringBoot可以令开发者“just run”就能创建一个独立的、生产级的应用。
简单来说,SpringBoot整合了很多优秀的框架,用来简化开发。我们在使用时只需要配置相应的Spring Boot,就可以使用所有的Spring组件,而无需再手动写很多xml配置文件。
2. HelloWorld入门案例
下面使用InteliJ IDEA写一个HelloWorld案例,简单了解一下SpringBoot。
2.1 项目构建
1)新建一个project,选择Spring Initializr,构建一个SpringBoot应用:
2)填写项目信息,即groupid与aritifactid,这里注意打包类型为Jar,确认jdk版本:
3)选择默认依赖,这里选择web,创建完成会自动引入spring web starter的依赖:
4)最后确认项目名称与路径:
5)至此,我们的springboot项目已构建完成,以下为项目结构:
其中src/main/java下存放java源代码;
src/main/resources/static存放静态资源文件;
src/main/resources/templates下存放模板引擎文件;src/main/resources/application.properties为SpringBoot的配置文件;
src/test下存放单元测试代码;
2.2 项目启动
1)首先我们查看POM文件,主要有jdk版本,及spring-boot-starter-web、spring-boot-starter-test两个起步依赖,具体版本在parent中已指出。
其中spring-boot-starter-web就是springboot的启动器之一,包含了tomcat、springmvc等jar,以支持全栈式的web开发。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.superchen</groupId>
<artifactId>spring-boot-hello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-hello</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2)我们发现自动创建了一个类SpringBootHelloApplication,这个类就是启动类,运行其中的main方法即启动项目:
package com.superchen.springboothello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootHelloApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHelloApplication.class, args);
}
}
3)运行main方法,启动项目,可从控制台信息中看到springboot的版本号、servlet引擎服务器tomcat及项目启动时间等:
2.3 HelloWorld案例
1)编写一个Controller,返回json数据,运行SpringBootHelloApplication的main方法启动项目(Controller用法与SpringMVC是完全相同的):
package com.superchen.springboothello.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
/**
* ClassName: HelloController <br/>
* Function: Spring Boot 入门案例HelloWorld控制器 . <br/>
* date: 2019/8/28 14:16 <br/>
*
* @author Chavaer
* @version 1.0.0
* @since JDK 1.8
*/
@RestController
public class HelloController {
@RequestMapping("/hello")
public Map<String, String> sayHello() {
Map<String, String> resultMap = new HashMap<String, String>();
resultMap.put("msg", "Hello World");
return resultMap;
}
}
2)浏览器访问http://localhost:8080/hello,即可正常访问: