0
点赞
收藏
分享

微信扫一扫

2-SpringBoot快速入门

2-SpringBoot快速入门

SpringBoot快速入门

需求:

搭建SpringBoot工程,定义HelloController.hello()方法,返回”Hello SpringBoot!”。

实现步骤:

①创建Maven项目

创建项目 springboot-helloworld 如下:


2-SpringBoot快速入门_spring

②导入SpringBoot起步依赖


2-SpringBoot快速入门_java_02

<!--springboot工程需要继承的父工程-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
</parent>

<dependencies>
<!--web开发的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

完整的 pom.xml 配置如下:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<!-- 项目的坐标 -->
<groupId>com.lijw</groupId>
<artifactId>springboot-helloworld</artifactId>
<version>1.0-SNAPSHOT</version>

<!--springboot工程需要继承的父工程-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
</parent>

<dependencies>
<!--web开发的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

</project>

③定义Controller


2-SpringBoot快速入门_spring boot_03

package com.lijw.controller;

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

/**
* @author Aron.li
* @date 2022/2/20 18:13
*/
@RestController
public class HelloController {

@RequestMapping("/hello")
public String hello(){
return "hello spring boot....";
}

}

在这里我们写了超简单的Controller,但是目前还是不能启动 SpringBoot,因为 SpringBoot 还需要一个启动引导类,用于启动 jar 包服务的时候的入口。

④编写引导类


2-SpringBoot快速入门_mybatis_04

package com.lijw;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* 引导类。SpringBoot项目的入口
* @author Aron.li
* @date 2022/2/20 18:16
*/
@SpringBootApplication // 说明这是SpringBoot应用
public class HelloApplication {

public static void main(String[] args) {
// 启动 SpringApplication 应用
SpringApplication.run(HelloApplication.class, args);
}
}

编写完启动引导类之后,我们就可以通过这个 main 方法来启动 SpringBoot。

⑤启动测试


2-SpringBoot快速入门_spring_052-SpringBoot快速入门_maven_06

从启动信息来看,默认端口号 8080,默认工程路径为空字符串,所以如果想要访问 HelloController,可以在浏览器访问如下:

​​http://localhost:8080/hello​​


2-SpringBoot快速入门_spring_07

测试成功!!

小结

  • SpringBoot 在创建项目时,使用 jar 的打包方式。
  • SpringBoot 的引导类是项目入口,运行main方法就可以启动项目。
  • 使用SpringBoot和Spring构建的项目,业务代码编写方式完全一样。


举报

相关推荐

0 条评论