SpringBoot系列(二) 环境搭建,创建我的第一个程序HelloWord。

环境准备:
  • jdk1.8:java version "1.8.0_231",详见链接
  • maven3.x:maven3.3以上版本,详见链接
  • IDEA2021:IntelliJ IDEA 2021.1.1 x64,详见链接
Spring Boot 之HelloWorld

功能:实现从web端发送接口请求,服务端收到请求并响应

1、使用Spring Initializr创建

1)File > New > Project

2)选中Spring Initializr,填写Artifact(项目名称)、Group(项目组织)、以及Package name(包名),和选择Loacation(项目存放的目录),点击Next

3)因为创建的是一个Web项目,所以引入Spring Web的相关组件,点击Finish

创建完成后的目录结构:

  • 代码目录:src/main/java/com.cavan.helloword
    HellowordApplication启动类

  • 资源目录:resource
    static:静态资源(jss css 图片 音频 视频)
    templates:模板文件(模板引擎freemarker thymeleaf 默认不支持jsp)
    application.properties:Spring boot默认的应用外部配置文件

  • 单元测试目录:test/java/com.cavan.helloword

  • 配置文件:pom.xml
    该文件用于管理源代码、打包方式、项目的依赖关系等等。

2、使用maven创建

1)File > New > Project,选择maven工程

为项目起个名字,这里helloworld-maven,然后点击Finish

2)引入web项目依赖

<!--web项目核心依赖-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
	<version> 2.3.7.RELEASE</version>
</dependency>
<!--测试依赖-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<version> 2.3.7.RELEASE</version>
	<scope>test</scope>
</dependency>

3)创建项目的入口类
在包com.cavan.helloworld下创建启动类HelloworldApplication

package com.cavan.helloworld;

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

/**
 * @program: helloworld-maven
 * @description: <description>
 * @author: cavan
 * @create: 2021-11-29 21:54
 */
@SpringBootApplication
public class HelloworldApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class);
    }
}

3、编写代码

通常,我们使用三层结构来编写。
应用层(Controller)、服务层(Service)、数据层(Dao)

我们在controller层增加HelloWorld类:

package com.cavan.helloword.controller;

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

/**
 * @program: helloword
 * @description: <description>
 * @author: cavan
 * @create: 2021-11-28 10:31
 */
@RestController
@RequestMapping(value = "")
public class HelloWord {
    @GetMapping(value = "hello")
    public String hello() {
        return "hello world";
    }
}

并在application.properties配置文件中修改服务端口:

server.port=8888

4、运行
4.1在本地idea运行

1)运行主程序 Run > Run 'HellowordApplication'

2)chorme浏览器访问http://localhost:8080/hello

4.2在Linux环境运行

1)通过mvn clean package 命令打包成helloword-0.0.1-SNAPSHOT.jar;
2)将jar包上传到/root目录下,使用java -jar helloword-0.0.1-SNAPSHOT.jar运行项目代码

3)使用curl访问服务,curl http://localhost:8888/hello

本文代码Gitee链接:
spring Initializr方式:https://gitee.com/cavan2021/springboot/tree/master/helloword
maven方式:https://gitee.com/cavan2021/springboot/tree/master/helloworld-maven

posted @ 2021-11-28 11:32  cavan丶keke  阅读(126)  评论(0编辑  收藏  举报