SpringBoot快速入门

1,165次阅读
没有评论

共计 2308 个字符,预计需要花费 6 分钟才能阅读完成。

前言:

SpringBoot是优化Spring操作的项目,它可以简化 Spring 应用的初始搭建和开发过程,让开发者能够更快速、更便捷地构建独立运行的、生产级别的 Spring 应用。

它的特点:自动配置起步依赖独立运行生产就绪特性

此文章是以Maven项目+jdk8环境下制作。制作功能:访问localhost:8080/hello 返回“Hello Spring Boot!“

SpringBoot快速入门:

  • 创建maven项目
  • 引入SpringBoot起步依赖
  • 定义controller
  • 编写引导类
  • 启动测试

制作过程:

① 首先创建项目:

SpringBoot快速入门

② 删除不必要的启动类

SpringBoot快速入门

③ 添加SpringBoot的起步依赖

SpringBoot快速入门

pom文件相关配置:

SpringBoot父工程依赖继承

<parent>
    <artifactId>spring-boot-starter-parent</artifactId>
    <groupId>org.springframework.boot</groupId>
    <version>2.5.0</version>
</parent>

web开发的起步依赖

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

完整pom

<?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>top.mcxxb.learn</groupId>
    <artifactId>LearnSpringBoot</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <!-- SpringBoot工程需要继承的父工程 -->
    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.5.0</version>
    </parent>
    <dependencies>
        <!--  web开发的起步依赖  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

别忘记右上角重载pom文件按钮

④ 编写启动类

SpringBoot快速入门
package top.mcxxb.springboot;

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

/**
* 引导类,SpringBoot项目入口
*/

@SpringBootApplication
public class HelloApplication {

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

}

⑤ 定义controller类

SpringBoot快速入门

完整代码:

package top.mcxxb.learn.controller;

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

@RestController
public class HelloController {

@RequestMapping("/hello")
public String hello(){
return "Hello Spring Boot!";
}

}

⑥ 启动项目

SpringBoot快速入门

此处启动采用的是Java自带的main方法,因此SpringBoot打包方式应该是jar包而非war包

⑦ 访问地址:localhost:8080/hello

SpringBoot快速入门

到此,你已经会快速搭建一个SpringBoot项目了

正文完
 0
评论(没有评论)