为了账号安全,请及时绑定邮箱和手机立即绑定

Spring Boot教程:从入门到实践

标签:
SpringBoot
概述

Spring Boot教程涵盖了从环境搭建到项目开发的全过程,包括依赖管理、自动配置、数据库集成以及日志和配置管理等内容,帮助开发者快速启动和运行一个Spring Boot项目。

Spring Boot简介

Spring Boot是什么

Spring Boot 是一个基于 Spring 框架的简化配置工具,它允许你快速搭建独立的、生产级别的 Spring 应用。由 Pivotal 团队提供,Spring Boot 的设计旨在简化 Spring 应用的初始搭建及开发过程。通过提供大量的默认配置,Spring Boot 可以帮助开发者快速启动项目,减少配置文件的编写工作。

Spring Boot的优势

  1. 快速启动:Spring Boot 提供了默认配置,使得开发者可以快速搭建应用,无需编写大量配置文件。
  2. 依赖管理:Spring Boot 自动管理依赖关系,自动将所需依赖添加到项目中。
  3. 嵌入式容器:支持内嵌 Tomcat、Jetty 或者 Undertow,无需部署到外部的 Web 服务器。
  4. 自动配置:根据添加的 jar 依赖包自动配置,简化了配置步骤,提高了开发效率。
  5. 命令行接口:Spring Boot 提供了一个内置的命令行界面(CLI)。

Spring Boot的核心概念

  1. 自动配置:Spring Boot 会根据添加的依赖包自动配置 Bean,简化了配置文件的编写。
  2. starter 依赖:每个 starter 依赖都包含了一系列其他的依赖,通过引入一个 starter 依赖,可以轻松地引入多个依赖。
  3. 外部化配置:Spring Boot 允许将配置信息从代码中分离出来,通过配置文件(如 application.properties 或 application.yml)进行管理。
  4. Actuator 端点:提供了应用状态的监控和管理功能。
环境搭建

开发工具准备

开发 Spring Boot 应用需要准备以下工具:

  1. Java 开发工具:推荐使用 IntelliJ IDEA 或 Eclipse。
  2. Java 开发环境:JDK 8 或更高版本。
  3. 本地搭建环境:需要安装 Maven 或 Gradle 作为构建工具。
  4. 数据库管理工具:如 MySQL、PostgreSQL 等数据库,可以使用 Navicat、phpMyAdmin 或其他数据库管理软件。

创建Spring Boot项目

可以通过 Spring Initializr 网站(https://start.spring.io/)创建 Spring Boot 项目。按照以下步骤操作:

  1. 选择项目类型:Spring Boot Project。
  2. 选择语言:Java。
  3. 选择依赖管理:Spring Boot 3.0.0 或更高版本。
  4. 选择构建工具:Maven 或 Gradle。
  5. 选择项目打包方式:Jar 或 War。
  6. 输入其他信息:如项目名、包名等。
  7. 点击 Generate,下载生成的压缩包。
  8. 解压文件,使用 IDE 打开项目。

配置本地环境

在项目的 pom.xmlbuild.gradle 文件中配置依赖:

使用 Maven 配置

<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>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

使用 Gradle 配置

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    runtimeOnly 'mysql:mysql-connector-java'
}
plugins {
    id 'org.springframework.boot'
}
第一个Spring Boot应用

创建控制器

创建一个简单的控制器来响应 HTTP 请求。

  1. src/main/java 目录下创建一个包,例如 com.example.demo.controller
  2. 在包内创建一个控制器类 HelloController
package com.example.demo.controller;

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!";
    }
}

运行和测试应用

  1. src/main/java 目录下创建一个主类 DemoApplication
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);
    }
}
  1. 运行 DemoApplication 类,启动应用。默认情况下,Spring Boot 应用会在 8080 端口上运行。
  2. 打开浏览器,访问 http://localhost:8080/hello,可以看到输出 "Hello, World!"。
Spring Boot常用注解详解

@SpringBootApplication

@SpringBootApplication 是一个组合注解,等同于以下三个注解:

  • @Configuration:表示当前类是一个配置类,可以包含配置信息。
  • @EnableAutoConfiguration:启用 Spring Boot 的自动配置功能。
  • @ComponentScan:指定扫描的包路径,自动识别和注册组件。
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);
    }
}

@Controller、@Service、@Repository、@Component

这些注解用于定义 Spring 组件,每个注解的功能略有不同:

  • @Controller:用于处理 HTTP 请求,通常用于定义 Web 控制器。
  • @Service:用于定义业务逻辑服务。
  • @Repository:用于数据访问层(如 DAO 层)。
  • @Component:通用的组件注解,适用于不需要特别指定类型的一般组件。
package com.example.demo.service;

import org.springframework.stereotype.Service;

@Service
public class MyService {
    public String sayHello() {
        return "Hello, Service!";
    }
}

@RestController、@RequestMapping

  • @RestController:等同于 @Controller@ResponseBody 的组合,用于构建 RESTful 风格的 Web 服务。
  • @RequestMapping:用于映射 HTTP 请求到控制器的方法。
package com.example.demo.controller;

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

import com.example.demo.service.MyService;

@RestController
@RequestMapping("/api")
public class MyController {
    private final MyService service;

    public MyController(MyService service) {
        this.service = service;
    }

    @GetMapping("/hello")
    public String hello() {
        return service.sayHello();
    }
}
数据库集成与使用

添加数据库依赖

pom.xmlbuild.gradle 文件中添加数据库依赖。例如,添加 MySQL 依赖:

使用 Maven

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

使用 Gradle

implementation 'mysql:mysql- #+#连接器'

配置数据库连接

application.propertiesapplication.yml 文件中配置数据库连接信息。

使用 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
spring.jpa.hibernate.ddl-auto=update

使用 YAML 文件

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

使用JPA进行数据库操作

  1. 创建实体类。
  2. 创建 Repository 接口。
  3. 创建 Service 层和 Controller 层。

实体类

package com.example.demo.entity;

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;

    // Getter 和 Setter 方法
}

Repository 接口

package com.example.demo.repository;

import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

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

Service 层

package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
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 Optional<User> findUserById(Long id) {
        return userRepository.findById(id);
    }

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

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

Controller 层

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

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> getAllUsers() {
        return userService.findAllUsers();
    }

    @PostMapping("/users")
    public User createUser(@RequestBody User user) {
        return userService.saveUser(user);
    }
}
日志和配置管理

使用Spring Boot的默认日志配置

Spring Boot 默认使用 Logback 作为日志框架,并且配置了默认的日志级别。可以在 application.propertiesapplication.yml 文件中自定义日志级别。

使用 properties 文件

logging.level.root=INFO
logging.level.com.example=DEBUG

使用 YAML 文件

logging:
  level:
    root: INFO
    com.example: DEBUG

自定义日志配置

可以创建自定义的日志配置文件 logback-spring.xml,具体配置如下:

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>

    <logger name="com.example" level="debug" />
</configuration>

外部化配置

外部化配置允许将配置信息从代码中分离出来,可以通过环境变量、命令行参数、配置文件等方式进行配置。

使用环境变量

可以通过环境变量设置配置值,例如:

export SPRING_DATASOURCE_URL=jdbc:mysql://localhost:3306/mydb

使用命令行参数

可以在启动应用时通过命令行参数传递配置值,例如:

java -jar target/demo.jar --spring.datasource.url=jdbc:mysql://localhost:3306/mydb

使用配置文件

可以使用 application.propertiesapplication.yml 文件指定配置值。例如:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消