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

Spring Boot企业级开发入门教程

RISEBY
关注TA
已关注
手记 496
粉丝 70
获赞 317
概述

本文全面介绍了Spring Boot企业级开发的基础,包括环境搭建、依赖管理、配置文件详解、RESTful API开发、数据库集成、安全配置、异常处理及部署监控。通过详细步骤和示例代码,帮助开发者快速构建高质量的企业级应用。

Spring Boot企业级开发入门教程
Spring Boot简介与环境搭建

Spring Boot是什么

Spring Boot 是一个基于Spring框架的开源项目,旨在简化新Spring应用的初始搭建以及开发过程。通过Spring Boot,开发者可以快速搭建一个独立的、生产级别的Spring应用。它通过提供默认配置和支持自动配置简化了开发流程,使得开发者不需要编写大量的XML或使用繁杂的注解就能快速创建一个独立的、生产级的应用程序。

开发环境搭建步骤

安装Java环境

  1. 下载并安装JDK:Oracle官网AdoptOpenJDK
  2. 验证安装:在命令行输入命令java -version,查看版本信息。

安装Maven

  1. 下载并安装Maven:Maven官网
  2. 配置环境变量:将Maven的bin目录路径添加到系统的PATH环境变量中。
  3. 验证安装:在命令行输入命令mvn -version,查看版本信息。

配置IDE

推荐IDE:IntelliJ IDEA、Eclipse或STS(Spring Tool Suite)

  1. IntelliJ IDEA

    • 下载并安装最新版本的IntelliJ IDEA:IntelliJ IDEA官网
    • 新建Spring Boot项目,使用File -> New -> Project,选择Spring Initializr,选择所需依赖。
  2. Eclipse

    • 下载并安装最新版本的Eclipse:Eclipse官网
    • 安装Spring Boot插件:在Eclipse Marketplace搜索Spring Tools,安装STS插件。
  3. STS(Spring Tool Suite)
    • 下载并安装最新版本的STS:STS官网
    • 使用STS直接创建Spring Boot项目。

创建本地Maven仓库

  1. 打开Maven的settings.xml文件,找到<localRepository>标签。
  2. 配置本地仓库路径,如:<localRepository>D:\maven\repository</localRepository>
  3. 使用Maven命令行或IDE创建本地仓库:mvn clean install

快速创建第一个Spring Boot项目

使用STS或IDEA创建一个简单的Spring Boot项目,以下是通过STS创建的例子:

  1. 打开STS,选择File -> New -> Spring Starter Project
  2. 输入项目名,选择语言(Java或Kotlin)、Spring Boot版本。
  3. 选择所需依赖,如Web、JPA、Thymeleaf等。
  4. 点击Finish

生成的项目结构如下:

src
└── main
    ├── java
    │   └── com
    │       └── example
    │           └── demo
    │               ├── DemoApplication.java
    │               └── DemoApplicationTests.java
    └── resources
        ├── application.properties
        └── static
            └── public
                └── images

完整的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>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
    </parent>
    <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>
    </dependencies>
</project>

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);
    }
}

项目运行

  1. 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);
    }
}
  1. 运行项目:
    • 在IDE中右键DemoApplication.java -> Run
    • 或者在命令行中运行:mvn spring-boot:run

在浏览器中访问http://localhost:8080/,如果看到默认的欢迎页面,说明项目已经成功运行。

企业级开发基础配置

使用Spring Boot的依赖管理

Maven依赖管理

Spring Boot项目通过Maven或Gradle管理依赖。以下是使用Maven的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>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
    </parent>
    <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>
    </dependencies>
</project>

添加自定义依赖

新建pom.xml并添加依赖:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

配置文件详解(application.properties和application.yml)

Spring Boot支持两种配置文件:application.propertiesapplication.yml

application.properties

默认情况下,Spring Boot会查找src/main/resources目录下的application.properties文件,该文件用于配置各种属性,如数据库连接、端口号等。

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/exampledb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

application.yml

application.yml文件是另一种配置文件格式,使用YAML语法,它更直观,适合复杂的配置。

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/exampledb
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

日志配置与管理

Spring Boot默认使用SLF4J作为日志门面,Logback作为实现。默认配置通常满足大部分需求,但可以自定义日志输出格式。

日志配置

src/main/resources目录下创建或覆盖logback-spring.xml文件,以自定义日志输出格式。

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} %5level %thread %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} %5level %thread %logger{36} - %msg%n</pattern>
        </encoder>
        <file>/var/log/myapp.log</file>
    </appender>
    <root level="info">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
</configuration>
实战项目开发

创建RESTful API接口

REST API是Web服务的一种标准,它基于HTTP协议,使用GET、POST、PUT、DELETE等HTTP方法操作资源。Spring Boot使用@RestController注解来创建RESTful服务。

示例代码

添加一个简单的REST API接口来获取用户信息:

package com.example.demo;

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

@RestController
public class UserController {

    @GetMapping("/users")
    public String getUsers() {
        return "List of Users";
    }
}

测试

在浏览器中访问http://localhost:8080/users,应该看到返回值为List of Users

数据库集成与操作

Spring Boot通过spring-boot-starter-data-jpa依赖集成数据库。这里以MySQL为例,展示如何连接数据库和进行CRUD操作。

配置数据库连接

application.properties中配置数据库连接:

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

创建实体类

创建一个User实体类,映射数据库中的users表:

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;

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

创建Repository

创建一个UserRepository接口,继承JpaRepository来简化数据库操作:

package com.example.demo;

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

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

创建服务层

创建UserService类,负责调用Repository操作数据库:

package com.example.demo;

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

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

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

创建控制器

创建UserController来处理HTTP请求:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

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

使用Spring Boot的内置Web服务器

Spring Boot使用嵌入式的Tomcat、Jetty或Undertow作为默认的Web服务器。开发者无需手动配置这些服务器,只需在pom.xml或者build.gradle中添加相应依赖即可。

使用Tomcat

默认情况下,Spring Boot使用Tomcat作为内置服务器。配置文件中无需改动,启动项目即使用Tomcat。

使用其他Web服务器

如果需要使用Jetty或Undertow,可以在pom.xml中添加相应依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
安全与权限管理

用户认证与授权

Spring Security是Spring生态中的安全模块,它为Web应用提供了强大的认证和授权支持。

配置Spring Security

pom.xml中添加Spring Security依赖:

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

配置安全设置

创建一个WebSecurityConfig类来配置Spring Security的安全设置:

package com.example.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
            .and()
            .logout()
                .permitAll();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

创建登录页面

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

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <form th:action="@{/login}" method="post">
        <label>Email</label>
        <input type="text" name="username" />
        <br>
        <label>Password</label>
        <input type="password" name="password" />
        <br>
        <button type="submit">Login</button>
    </form>
</body>
</html>

使用Spring Security进行安全配置

安全配置示例

WebSecurityConfig类中配置不同的安全规则:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
                .antMatchers("/", "/home").permitAll()
            .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
            .and()
            .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
                .and()
                .withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

实现登录、用户权限控制

登录过程

用户访问登录页面,输入用户名和密码,点击登录按钮,Spring Security会验证输入的用户名和密码,如果验证通过则跳转到主页,否则显示错误信息。

用户权限控制

通过@PreAuthorize@Secured注解控制对某些资源的访问权限。

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AdminController {

    @Autowired
    private UserService userService;

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin")
    public String admin() {
        return "Admin Page";
    }
}
异常处理与日志记录

捕获和处理异常

Spring Boot提供了两种处理异常的方式:全局异常处理和控制器级别的异常处理。

全局异常处理

定义一个全局异常处理器类,实现org.springframework.web.bind.annotation.ControllerAdviceorg.springframework.web.bind.annotation.ExceptionHandler注解。

package com.example.demo;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {Exception.class})
    public ResponseEntity<String> handleException(Exception e) {
        return new ResponseEntity<>("An error occurred", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

控制器级别的异常处理

在具体的控制器中捕获和处理异常。

package com.example.demo;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@ControllerAdvice
public class UserController {

    @GetMapping("/users")
    public String getUsers() {
        throw new RuntimeException("Error fetching users");
    }

    @ExceptionHandler(value = {Exception.class})
    public ResponseEntity<String> handleException(Exception e) {
        return new ResponseEntity<>("An error occurred", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

自定义异常处理

创建自定义异常类,并在控制器中抛出自定义异常。

自定义异常类

package com.example.demo;

public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(String message) {
        super(message);
    }
}

控制器中的自定义异常处理

package com.example.demo;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/users")
    public String getUsers() {
        throw new UserNotFoundException("User not found");
    }

    @ExceptionHandler(value = {UserNotFoundException.class})
    public ResponseEntity<String> handleUserNotFoundException(UserNotFoundException e) {
        return new ResponseEntity<>(e.getMessage(), HttpStatus.NOT_FOUND);
    }
}

使用SLF4J和Logback进行日志记录

在代码中使用SLF4JLogger记录日志信息。

package com.example.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/users")
    public String getUsers() {
        logger.info("Getting users");
        return "List of Users";
    }
}
部署与监控

打包与部署Spring Boot应用

Spring Boot应用可以通过Maven或Gradle构建工具进行打包。打包后生成的jar文件可以直接运行,也可以通过Docker进行容器化部署。

使用Maven打包

在项目根目录下运行命令mvn clean package,生成的jar文件位于target目录下。

使用Docker打包

创建一个Dockerfile,示例如下:

FROM openjdk:8-jre-alpine
VOLUME /tmp
COPY target/*.jar app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

使用命令docker build -t myapp:latest .构建镜像,运行命令docker run -p 8080:8080 myapp:latest启动容器。

应用监控与健康检查

Spring Boot内置了Actuator组件,提供了丰富的生产特性如健康检查、线程信息等。

启用Actuator

pom.xml中添加Actuator依赖:

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

启用健康检查端点

application.properties中启用健康检查端点:

management.endpoints.web.exposure.include=health,info

访问http://localhost:8080/actuator/health获取应用健康状态。

使用Docker容器化部署

Docker容器化部署可以简化应用的部署和维护过程。

Dockerfile示例

FROM openjdk:8-jre-alpine
VOLUME /tmp
COPY target/*.jar app.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

构建并运行Docker镜像

编译代码后,运行以下命令:

docker build -t myapp:latest .
docker run -p 8080:8080 myapp:latest

监控应用

使用工具如Prometheus、Grafana等进行应用的监控和可视化。

  1. Prometheus

    • 配置Prometheus监控Spring Boot应用。
    • 在Prometheus配置文件中添加应用的监控端点。
  2. Grafana
    • 使用Grafana创建监控面板。
    • 配置Grafana与Prometheus进行数据源配置。

通过以上步骤,可以有效地监控应用的运行状态和性能指标。

总结

通过本教程,我们全面介绍了Spring Boot企业级应用的基础开发与配置方法,包括环境搭建、基础配置、实战项目开发、安全与权限管理、异常处理与日志记录、部署与监控等。这些内容为开发者提供了一个全面的Spring Boot开发指南,有助于开发者快速构建高质量的企业级应用。

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