亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Springboot項目開發教程:初學者指南

標簽:
SpringBoot

本文详细介绍如何从零开始开发一个Spring Boot项目,涵盖了环境搭建、基础配置、控制器开发、数据库操作及测试等关键步骤。通过本文,你将学会如何快速搭建和运行一个Spring Boot应用,并掌握其核心特性和开发技巧。本文旨在帮助开发者快速上手并高效构建Spring Boot应用。

Spring Boot简介

什么是Spring Boot

Spring Boot 是由Pivotal团队提供的开源框架,旨在简化Spring应用程序的开发过程。Spring Boot提供了一种快速构建独立的、生产级别的基于Spring框架的应用程序的方式。它通过约定优于配置的原则,极大地简化了配置过程。开发人员可以专注于编写业务逻辑,而无需过多关注底层配置细节。

Spring Boot的优势

Spring Boot的主要优势包括:

  1. 简化配置:许多常用的配置都可以通过注解或默认值来简化。
  2. 嵌入式Web服务器:可以将应用与嵌入式的Tomcat、Jetty或Undertow服务器一起部署,无需单独部署到外部服务器。
  3. 自动配置:通过自动配置,Spring Boot可以自动配置许多常见的需求,例如数据源、JPA、缓存等。
  4. 快速启动:提供了快速的启动时间和开发周期,适合敏捷开发。
  5. 嵌入式支持:支持嵌入式的HTTP服务器,简化了部署步骤。
  6. 依赖管理:提供了默认的依赖版本管理,避免了版本冲突。
  7. 健康检查和监控:内置了健康检查和监控功能,便于管理和维护。
  8. 嵌入式文档:使用spring-boot-actuator模块,提供了内置的健康检查、信息提供和运行时指标收集等功能。

快速入门示例

  1. 安装Java环境

    首先确保已安装Java环境,并设置好环境变量。可以通过命令 java -version 检查Java版本。

  2. 创建Spring Boot项目

    使用Spring Initializr (在线工具) 或者命令行工具spring init来创建项目。这里演示使用命令行工具创建项目:

    spring init --dependencies=web --groupId=com.example --artifactId=springbootdemo --version=1.0.0 --packaging=jar demo

    上述命令创建了一个包含Web依赖的Spring Boot项目,项目名为 demo,其包名为 com.example,版本为 1.0.0,打包格式为 jar

  3. 项目目录结构

    项目目录结构如下:

    demo/
       ├── src/
       │   ├── main/
       │   │   ├── java/
       │   │   │   └── com/
       │   │   │       └── example/
       │   │   │           └── demo/
       │   │   │               └── DemoApplication.java
       │   │   └── resources/
       │   │       └── application.properties
       │   └── test/
       │       └── java/
       │           └── com/
       │               └── example/
       │                   └── demo/
       │                       └── DemoApplicationTests.java
       └── pom.xml
  4. 运行项目

    DemoApplication.java 文件中编写启动类:

    package com.example.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class DemoApplication {
       public static void main(String[] args) {
           SpringApplication.run(DemoApplication.class, args);
       }
    }

    然后运行以下命令启动应用:

    ./mvnw spring-boot:run

    或者使用IDE进行运行。

    当Spring Boot应用成功启动后,可以通过访问 http://localhost:8080 来验证应用是否运行正常。

环境搭建

开发环境准备

开发环境准备包括安装Java和选择IDE。这里推荐使用IntelliJ IDEA或Eclipse。在安装完Java和IDE后,需要安装Spring Boot插件或工具。

安装Java

确保安装Java并设置好环境变量。可以通过命令 java -version 检查Java版本。

安装IDE

  • IntelliJ IDEA:从菜单 File -> New -> Project 选择 Spring Initializr,然后选择 MavenGradle,选择所需依赖后创建项目。
  • Eclipse:通过 File -> New -> Spring Starter Project 创建项目,并选择依赖项。

Spring Boot项目创建

  1. 使用IDE

    • IntelliJ IDEA:从菜单 File -> New -> Project 选择 Spring Initializr,然后选择 MavenGradle,选择所需依赖后创建项目。
    • Eclipse:通过 File -> New -> Spring Starter Project 创建项目,并选择依赖项。
  2. 使用命令行工具

    使用 spring init 命令来创建一个项目,示例如前文中的 spring init 示例。

项目依赖管理

pom.xml 文件中管理项目依赖。例如:

<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.example</groupId>
    <artifactId>demo</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </build>
</project>
基础配置

配置文件介绍(application.properties/application.yml)

Spring Boot 支持两种配置文件:application.propertiesapplication.yml。这两种文件存储在 src/main/resources 目录下。

  • application.properties

    示例:

    server.port=8080
    server.servlet.context-path=/api
    spring.datasource.url=jdbc:mysql://localhost:3306/testdb
    spring.datasource.username=root
    spring.datasource.password=root
  • application.yml

    示例:

    server:
    port: 8080
    servlet:
      contextPath: /api
    spring:
    datasource:
      url: jdbc:mysql://localhost:3306/testdb
      username: root
      password: root

配置属性的使用

可以通过 @Value 注解或者 @ConfigurationProperties 注解来注入配置属性。这里介绍 @Value 的使用:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class AppConfig {
    @Value("${server.port}")
    private int serverPort;

    public int getServerPort() {
        return serverPort;
    }
}

自定义配置属性

可以通过创建一个类来定义自定义配置属性:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "custom")
public class CustomConfig {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

然后在配置文件中添加对应的属性:

custom.name=John
custom.age=30
控制器开发

创建控制器类

控制器类通常使用 @Controller@RestController 注解标记。这里使用 @RestController,这是 @Controller@ResponseBody 的组合。

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

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

处理HTTP请求

控制器类可以处理各种HTTP请求,包括 GETPOSTPUTDELETE 等。这里以处理 POST 请求为例:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @PostMapping("/user")
    public String createUser(@RequestParam String name, @RequestParam int age) {
        return "Name: " + name + ", Age: " + age;
    }
}

模板引擎介绍与使用

Spring Boot 支持多种模板引擎,如 Thymeleaf、FreeMarker 等。这里以 Thymeleaf 为例,首先需要在 pom.xml 中添加相关依赖:

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

然后在控制器中返回一个视图:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {
    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("message", "Hello, World!");
        return "hello";
    }
}

src/main/resources/templates 目录下创建 hello.html 文件:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello Page</title>
</head>
<body>
    <h1 th:text="${message}"></h1>
</body>
</html>
数据库操作

连接数据库

Spring Boot通过自动配置来简化数据库连接。默认情况下,Spring Boot会根据 application.propertiesapplication.yml 文件中的配置自动连接数据库。

示例配置:

spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update

数据库操作(CRUD)

使用 JPA 进行数据库操作。首先定义一个实体类:

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 int age;

    // 构造函数、getter和setter方法
}

然后创建一个 UserRepository

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

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

示例 CRUD 操作:

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

@RestController
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @PostMapping("/user")
    public User createUser(@RequestParam String name, @RequestParam int age) {
        User user = new User();
        user.setName(name);
        user.setAge(age);
        return userRepository.save(user);
    }

    @GetMapping("/users")
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable Long id) {
        return userRepository.findById(id).orElse(null);
    }

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

数据库连接池配置

Spring Boot默认使用HikariCP作为数据库连接池。可以在 application.properties 中配置连接池参数:

spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.max-lifetime=1800000
路由与测试

基本路由配置

Spring Boot使用Spring MVC的@RequestMapping注解来定义路由映射。例如:

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

@RestController
@RequestMapping("/api")
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, World!";
    }
}

单元测试

创建单元测试类:

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.boot.web.server.LocalServerPort;

import static org.assertj.core.api.Assertions.assertThat;

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

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void contextLoads() {
        String body = this.restTemplate.getForObject("http://localhost:" + port + "/hello", String.class);
        assertThat(body).isEqualTo("Hello, World!");
    }
}

整合测试

创建整合测试类:

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;

import static org.assertj.core.api.Assertions.assertThat;

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

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void contextLoads() {
        String body = this.restTemplate.getForObject("http://localhost:" + port + "/user", String.class);
        assertThat(body).isEqualTo("Hello, World!");
    }
}

通过上述内容,你可以了解如何从零开始构建一个Spring Boot项目,并涵盖了环境搭建、基础配置、控制器开发、数据库操作、路由与测试等方面的知识。希望这些信息能帮助你快速上手Spring Boot开发。

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消