继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Springboot3+JDK17搭建后端学习的简单教程

慕码人8056858
关注TA
已关注
手记 1285
粉丝 351
获赞 1323
概述

本文详细讲解了如何使用Spring Boot 3和JDK 17搭建后端应用,涵盖从环境配置到项目搭建,再到数据库集成和测试部署的全过程。通过Spring Boot 3和Java 17的新特性,开发者可以构建高效稳定的后端应用。文章还介绍了如何创建RESTful API和服务,并通过Spring Boot Actuator进行监控。

引入Spring Boot 3和JDK 17

为什么选择Spring Boot 3和JDK 17

Spring Boot 3是Spring Boot的最新版本,提供了许多新特性和改进,同时也引入了对Java 17的支持。以下是选择Spring Boot 3和JDK 17的原因:

  1. Java 17的新特性:Java 17引入了许多新特性和改进,例如Sealed Types、Pattern Matching for instanceof等,这些特性可以提高代码的可读性和安全性。
  2. Spring Boot 3的优势:Spring Boot 3不仅支持Java 17,还提供了一系列新特性和改进,例如更优化的依赖管理和启动性能。同时,它还支持非阻塞Web应用、改进的安全模型等。
  3. 长期支持版本:Java 17是长期支持版本(Long Term Support,LTS),这意味着它会获得更长时间的支持和补丁更新,更适合生产环境。

安装和配置JDK 17

为了使用Spring Boot 3和JDK 17,首先需要安装和配置JDK 17。

  1. 下载JDK 17:在Oracle官网或OpenJDK官网下载JDK 17的安装包。
  2. 安装JDK 17:解压安装包,并将JDK安装路径添加到环境变量中。
  3. 验证安装:打开命令行,输入以下命令验证JDK 17是否安装成功:

    java -version

    输出应该显示Java版本为17。

  4. 设置JAVA_HOME环境变量:确保JAVA_HOME环境变量指向JDK 17的安装路径,并将%JAVA_HOME%\bin添加到系统的PATH环境变量中。

创建Spring Boot 3项目

  1. 创建新项目:使用Spring Initializr(http://start.spring.io)创建一个新的Spring Boot项目。在Spring Initializr中选择Maven或Gradle作为构建工具,选择Java 17作为Java版本,选择Spring Boot 3.x作为版本。
  2. 添加基础依赖:选择WebJPA等依赖,可以自定义项目需要的功能模块。
  3. 导入项目:将创建的项目导入到IDE(如IntelliJ IDEA、Eclipse等)中。

使用Spring Initializr创建项目后,项目基本结构如下:

- src
  - main
    - java
      - com.example.demo
        - DemoApplication.java
        - YourController.java
    - resources
      - application.properties
      - application.yml
  - test
    - java
      - com.example.demo
        - YourControllerTest.java

项目结构和基本配置

了解Spring Boot项目的基本结构

Spring Boot项目的基本结构如下:

  • src/main/java:存放Java源代码,包括应用主类、控制器(Controller)、服务(Service)、实体类(Entity)等。
  • src/main/resources:存放资源文件,例如配置文件(application.propertiesapplication.yml)、静态资源文件、模板文件等。
  • src/test/java:存放测试代码,例如单元测试(JUnit)。

配置文件详解(application.properties/application.yml

Spring Boot使用配置文件来管理应用的各种配置。可以使用application.propertiesapplication.yml来配置。

application.properties示例:

# 应用端口号
server.port=8080

# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Spring Data JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

application.yml示例:

server:
  port: 8080

spring:
  datasource:
  url: jdbc:mysql://localhost:3306/mydb
  username: root
  password: root
  driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
  hibernate:
    ddl-auto: update
  show-sql: true
  properties:
    hibernate:
      dialect: org.hibernate.dialect.MySQL5InnoDBDialect

引入依赖和自动配置

在项目的pom.xmlbuild.gradle文件中,添加必要的依赖,例如Web、JPA等。

pom.xml示例:

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

build.gradle示例:

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-web'
  implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
  implementation 'mysql:mysql-connector-java'
  testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

创建简单的RESTful API

创建第一个Controller

创建一个RESTful API的Controller,用于处理HTTP请求。

Controller示例:

package com.example.demo;

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

@RestController
public class YourController {

  @GetMapping("/hello")
  public String hello() {
    return "Hello, World!";
  }
}

返回JSON数据

在Controller中返回JSON数据。

Controller示例:

package com.example.demo;

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

@RestController
public class YourController {

  @GetMapping("/greet")
  public Greeting greet() {
    return new Greeting("Hello, World!");
  }

  static class Greeting {
    private String message;

    public Greeting(String message) {
      this.message = message;
    }

    public String getMessage() {
      return message;
    }
  }
}

使用Spring Boot的内置服务器启动项目

启动项目以验证RESTful API是否可以正常运行。

启动应用:

mvn spring-boot:run

或在IDE中运行DemoApplication类中的main方法。

访问http://localhost:8080/greet,应该会返回JSON数据:

{
  "message": "Hello, World!"
}

数据库集成

连接MySQL数据库

在项目配置文件中添加MySQL数据库连接配置。

application.properties示例:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

application.yml示例:

spring:
  datasource:
  url: jdbc:mysql://localhost:3306/mydb
  username: root
  password: root
  driver-class-name: com.mysql.cj.jdbc.Driver

使用Spring Data JPA进行数据库操作

创建一个实体类(Entity),并实现简单的CRUD操作。

Entity示例:

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String name;
  private String email;

  // Getters and Setters
}

Repository示例:

package com.example.demo;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}

Service示例:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {

  private final UserRepository userRepository;

  @Autowired
  public UserService(UserRepository userRepository) {
    this.userRepository = userRepository;
  }

  public List<User> findAllUsers() {
    return userRepository.findAll();
  }

  public User findUserById(Long id) {
    Optional<User> optionalUser = userRepository.findById(id);
    return optionalUser.orElse(null);
  }

  public User saveUser(User user) {
    return userRepository.save(user);
  }

  public void deleteUser(Long id) {
    userRepository.deleteById(id);
  }
}

实现简单的CRUD操作

创建一个Controller来处理用户相关的HTTP请求。

Controller示例:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

  private final UserService userService;

  @Autowired
  public UserController(UserService userService) {
    this.userService = userService;
  }

  @GetMapping("/users")
  public List<User> listUsers() {
    return userService.findAllUsers();
  }

  @GetMapping("/user/{id}")
  public User getUser(@PathVariable Long id) {
    return userService.findUserById(id);
  }

  @PostMapping("/user")
  public User createUser(@RequestBody User user) {
    return userService.saveUser(user);
  }

  @DeleteMapping("/user/{id}")
  public void deleteUser(@PathVariable Long id) {
    userService.deleteUser(id);
  }
}

测试和调试

使用JUnit进行单元测试

创建JUnit单元测试,验证Controller和Service的正确性。

测试示例:

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {

  @Autowired
  private TestRestTemplate restTemplate;

  @Test
  public void testListUsers() {
    // Assuming the database is empty initially
    ResponseEntity<User[]> response = restTemplate.getForEntity("/users", User[].class);
    assertEquals(0, response.getBody().length);
  }

  @Test
  public void testCreateUser() {
    User user = new User();
    user.setName("Test User");
    user.setEmail("test@example.com");

    ResponseEntity<User> response = restTemplate.postForEntity("/user", user, User.class);
    assertEquals(201, response.getStatusCodeValue());
    assertEquals("Test User", response.getBody().getName());
  }

  @Test
  public void testGetUser() {
    User user = new User();
    user.setName("Test User");
    user.setEmail("test@example.com");
    User createdUser = restTemplate.postForEntity("/user", user, User.class).getBody();

    User fetchedUser = restTemplate.getForEntity("/user/{id}", User.class, createdUser.getId()).getBody();
    assertEquals("Test User", fetchedUser.getName());
  }

  @Test
  public void testDeleteUser() {
    User user = new User();
    user.setName("Test User");
    user.setEmail("test@example.com");
    User createdUser = restTemplate.postForEntity("/user", user, User.class).getBody();

    restTemplate.delete("/user/{id}", createdUser.getId());

    User fetchedUser = restTemplate.getForEntity("/user/{id}", User.class, createdUser.getId()).getBody();
    assertEquals(null, fetchedUser);
  }
}

使用Spring Boot Actuator进行健康检查和监控

Spring Boot Actuator是一个提供生产就绪功能的库,用于监控和管理应用。启用Actuator可以进行健康检查和监控。

配置Actuator:

pom.xmlbuild.gradle中添加Actuator依赖。

pom.xml示例:

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

build.gradle示例:

implementation 'org.springframework.boot:spring-boot-starter-actuator'

启用Actuator后,可以通过/actuator端点访问监控信息。

部署和运行

打包成可执行的JAR文件

使用Maven或Gradle将项目打包成可执行的JAR文件。

使用Maven打包:

mvn clean package

输出的JAR文件位于target目录下。

使用Gradle打包:

./gradlew bootJar

输出的JAR文件位于build/libs目录下。

部署到远程服务器

将打包好的JAR文件上传到远程服务器,例如使用SCP或FTP上传。

上传JAR文件示例:

scp target/demo-0.0.1-SNAPSHOT.jar user@remote.server.com:/path/to/deploy

运行和访问应用

在远程服务器上运行JAR文件。

运行JAR文件示例:

java -jar demo-0.0.1-SNAPSHOT.jar

访问应用的端点,例如http://remote.server.com:8080/users,验证应用是否正常运行。

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP