首页 > 技术文章 > Springboot:第一个Springboot程序(一)

applesnt 2020-04-10 10:10 原文

1、创建Springboot项目

选择创建Springboot项目:

填写项目基本信息:

选择Springboot版本以及web依赖(内嵌tomcat):

创建完成:

创建完成后 等待构建maven项目,需要下载项目依赖的环境!

构建完成后的项目结构:

2、Springboot目录结构:

com.springboot: 创建的默认包名,spring默认扫描的包路径

HellospringbootApplication:主程序入口,启动项目

resources:配置文件类路径 一般用于存放配置文件

static:静态文件目录 css js等

templates:模板目录 thymeleaf、freemarker

application.properties:springboot的主配置文件

HellospringbootApplicationTests:测试主程序类

pom.xml:maven依赖环境配置

3、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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!--父项目 springboot版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <!--项目坐标:gav-->
    <groupId>com.springboot</groupId>
    <artifactId>hellospringboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hellospringboot</name>
    <description>Demo project for Spring Boot</description>

    <!--jdk版本-->
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <!--环境依赖-->
    <dependencies>

        <!--web环境依赖,会自动装配tomcat、静态资源目录、templates目录-->
        <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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <!--maven打包插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

4、程序测试

构建一个controller:
com.springboot.controller.HelloController

package com.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/*第一个Springboot程序*/
@Controller
public class HelloController {

    @GetMapping("/hello")
    @ResponseBody
    public String  helloWorld(){
        return "Hello Springboot";
    }
}

启动项目:默认端口8080

访问项目:

5、程序打包运行

maven-package

打包成功后,会在程序的target目录下生成一个jar包

cmd进入jar的所在目录,用java -jar运行jar包

启动成功

访问项目:

推荐阅读