MK
摩柯社区 - 一个极简的技术知识社区
AI 面试

Java编程中的Spring Boot入门指南

2021-03-056.7k 阅读

1. 环境搭建

在开始使用Spring Boot进行Java编程之前,我们需要搭建好相应的开发环境。主要涉及JDK、Maven以及IDE的安装与配置。

1.1 JDK安装

首先,确保你的机器上安装了Java Development Kit(JDK)。Spring Boot通常要求JDK 8或更高版本。你可以从Oracle官方网站或者OpenJDK项目官网下载适合你操作系统的JDK安装包。

以Windows系统为例,下载完成后,双击安装包,按照安装向导提示进行安装。安装过程中,可以自定义安装路径,但要记住安装目录,后续配置环境变量会用到。

安装完成后,需要配置系统环境变量。在“系统属性” -> “高级” -> “环境变量”中,新建一个系统变量 JAVA_HOME,变量值为JDK的安装目录,例如 C:\Program Files\Java\jdk11.0.12。然后在 Path 变量中添加 %JAVA_HOME%\bin%JAVA_HOME%\jre\bin,这样系统就能够找到Java的可执行文件。

在命令行中输入 java -version,如果显示出JDK的版本信息,说明JDK安装和配置成功。

1.2 Maven安装

Maven是一个Java项目管理工具,Spring Boot项目通常使用Maven来管理依赖和构建项目。你可以从Maven官方网站下载Maven的二进制压缩包。

下载完成后,解压压缩包到你希望的安装目录,例如 C:\apache-maven-3.8.4。同样,需要配置系统环境变量。新建一个系统变量 MAVEN_HOME,变量值为Maven的安装目录。然后在 Path 变量中添加 %MAVEN_HOME%\bin

在命令行中输入 mvn -version,如果显示出Maven的版本信息,说明Maven安装和配置成功。

1.3 IDE选择与配置

对于Spring Boot开发,有很多优秀的IDE可供选择,如IntelliJ IDEA、Eclipse等。这里以IntelliJ IDEA为例。

下载并安装IntelliJ IDEA后,打开IDEA。如果是首次使用,IDEA会引导你进行一些初始设置,如选择主题、设置项目默认路径等。

在IDEA中,你可以通过 File -> Settings(Windows/Linux)或 IntelliJ IDEA -> Preferences(Mac)打开设置窗口。在 Build, Execution, Deployment -> Build Tools -> Maven 中,设置Maven的安装目录和 settings.xml 文件路径(通常在Maven安装目录的 conf 文件夹下)。同时,在 Project Structure 中,可以设置项目的SDK,选择你安装好的JDK。

2. 创建第一个Spring Boot项目

2.1 使用Spring Initializr

Spring Initializr是一个快速创建Spring Boot项目的在线工具,同时也集成在很多IDE中。

打开浏览器,访问 https://start.spring.io/。在网页上,你可以进行如下配置:

  • Project:选择 MavenGradle,这里我们选择 Maven
  • Language:选择 Java
  • Spring Boot:选择你想要的Spring Boot版本,通常选择最新的稳定版本。
  • Group:这是项目的组,类似于Java包名的前缀,例如 com.example
  • Artifact:这是项目的名称,例如 my - first - spring - boot - app
  • Name:项目名称,默认为Artifact的值。
  • Description:项目描述。
  • Package Name:默认与Group和Artifact组成的包名一致,你也可以自定义。
  • Dependencies:这里可以添加项目所需的依赖。例如,如果你想创建一个Web应用,就添加 Spring Web 依赖。

配置完成后,点击 Generate 按钮,会下载一个压缩包。解压压缩包,就得到了一个基本的Spring Boot项目结构。

2.2 在IntelliJ IDEA中创建项目

打开IntelliJ IDEA,选择 Create New Project。在弹出的窗口中,左侧选择 Spring Initializr,右侧可以进行与Spring Initializr网页版类似的配置。完成配置后,点击 Next,然后选择项目的存储路径,最后点击 Finish,IDEA会自动下载项目所需的依赖并创建项目结构。

3. Spring Boot项目结构解析

一个典型的Spring Boot项目结构如下:

my - first - spring - boot - app
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── myfirstspringbootapp
│   │   │               ├── MyFirstSpringBootAppApplication.java
│   │   ├── resources
│   │   │   ├── application.properties
│   │   │   └── static
│   │   │       └──...
│   │   │   └── templates
│   │   │       └──...
│   └── test
│       ├── java
│       │   └── com
│       │       └── example
│       │           └── myfirstspringbootapp
│       │               ├── MyFirstSpringBootAppApplicationTests.java
│       └── resources
├── target
├── pom.xml

3.1 主程序类

MyFirstSpringBootAppApplication.java 是Spring Boot项目的主程序类。它通常包含一个带有 @SpringBootApplication 注解的主类和一个 main 方法。例如:

package com.example.myfirstspringbootapp;

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

@SpringBootApplication
public class MyFirstSpringBootAppApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyFirstSpringBootAppApplication.class, args);
    }
}

@SpringBootApplication 是一个组合注解,它包含了 @Configuration@EnableAutoConfiguration@ComponentScan 三个注解的功能。@Configuration 表示该类是一个配置类,@EnableAutoConfiguration 让Spring Boot根据类路径下的依赖自动配置Spring应用,@ComponentScan 用于扫描指定包及其子包下的组件,将其注册到Spring容器中。

main 方法通过 SpringApplication.run 方法启动Spring Boot应用。

3.2 配置文件

application.properties(或 application.yml)是Spring Boot的主要配置文件,位于 src/main/resources 目录下。在这个文件中,你可以配置各种应用程序属性,如服务器端口、数据库连接信息等。例如,要修改应用程序的端口号,可以在 application.properties 中添加:

server.port = 8081

3.3 静态资源和模板文件

src/main/resources/static 目录用于存放静态资源,如CSS、JavaScript、图片等。这些资源可以直接通过URL访问,例如 http://localhost:8080/css/style.css

src/main/resources/templates 目录用于存放模板文件,如Thymeleaf、Freemarker等模板引擎的模板文件。Spring Boot默认支持Thymeleaf模板引擎,通过模板引擎可以动态生成HTML页面。

3.4 测试类

MyFirstSpringBootAppApplicationTests.java 是Spring Boot项目的测试类,位于 src/test/java 目录下。它用于对项目进行单元测试和集成测试。例如:

package com.example.myfirstspringbootapp;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class MyFirstSpringBootAppApplicationTests {
    @Test
    void contextLoads() {
    }
}

@SpringBootTest 注解用于加载Spring Boot应用上下文,进行集成测试。contextLoads 方法是一个简单的测试方法,目前为空,你可以在其中添加具体的测试逻辑。

4. 创建Web应用

Spring Boot对Web开发提供了强大的支持,通过添加 Spring Web 依赖,我们可以快速创建一个Web应用。

4.1 添加依赖

pom.xml 文件中添加 Spring Web 依赖:

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

Maven会自动下载该依赖及其相关的依赖库。

4.2 创建Controller

Controller是处理Web请求的组件。在 com.example.myfirstspringbootapp 包下创建一个新的类,例如 HelloController.java

package com.example.myfirstspringbootapp;

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

@RestController 注解表示该类是一个处理HTTP请求的控制器,并且返回的数据会以JSON或XML等格式直接写入HTTP响应体,而不是返回一个视图。@GetMapping("/hello") 注解表示该方法处理HTTP GET请求,请求路径为 /hello。当访问 http://localhost:8080/hello 时,会返回 Hello, Spring Boot!

4.3 启动应用并测试

运行 MyFirstSpringBootAppApplicationmain 方法,启动Spring Boot应用。然后打开浏览器,访问 http://localhost:8080/hello,你应该能看到页面上显示 Hello, Spring Boot!

5. 配置文件详解

Spring Boot的配置文件支持多种格式,最常用的是 propertiesyml 格式。

5.1 properties格式

application.properties 文件中,配置属性以 key = value 的形式书写。例如:

# 配置服务器端口
server.port = 8081

# 配置日志级别
logging.level.root = info

5.2 yml格式

yml 格式的配置文件使用缩进和冒号来表示层次结构,更加简洁易读。将 application.properties 转换为 application.yml 如下:

server:
  port: 8081
logging:
  level:
    root: info

5.3 配置文件的加载顺序

Spring Boot会按照以下顺序加载配置文件:

  1. 命令行参数:通过命令行传递的配置参数优先级最高,例如 java -jar myapp.jar --server.port = 8082
  2. SPRING_APPLICATION_JSON 中的属性:可以通过环境变量 SPRING_APPLICATION_JSON 来设置JSON格式的配置属性。
  3. ServletConfig 初始化参数:在 web.xml 中设置的初始化参数。
  4. ServletContext 初始化参数:同样在 web.xml 中设置。
  5. java:comp/env 中的JNDI属性:如果应用部署在支持JNDI的容器中。
  6. System.getProperties():Java系统属性。
  7. 操作系统环境变量
  8. RandomValuePropertySource:用于生成随机数的配置源,例如 random.int
  9. application.propertiesapplication.yml:包括 file:./config/file:./classpath:/config/classpath:/ 四个位置的配置文件,后面加载的会覆盖前面的。
  10. @TestPropertySource:测试环境下使用的配置。
  11. DefaultPropertiesPropertySource:默认的配置源。

5.4 自定义配置属性

在Spring Boot中,我们可以自定义配置属性。首先,在 application.properties 中定义属性:

myapp.message = Hello from custom property

然后,创建一个Java类来绑定这些属性。例如,创建 MyAppProperties.java

package com.example.myfirstspringbootapp;

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

@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
    private String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

@ConfigurationProperties(prefix = "myapp") 注解表示将 application.properties 中以 myapp 为前缀的属性绑定到该类的属性上。

最后,在Controller中使用这个属性:

package com.example.myfirstspringbootapp;

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

@RestController
public class CustomPropertyController {
    @Autowired
    private MyAppProperties myAppProperties;

    @GetMapping("/custom - message")
    public String customMessage() {
        return myAppProperties.getMessage();
    }
}

访问 http://localhost:8080/custom - message,会返回 Hello from custom property

6. 数据访问

Spring Boot对各种数据访问技术都提供了良好的支持,包括关系型数据库(如MySQL、PostgreSQL)和非关系型数据库(如MongoDB、Redis)。

6.1 访问MySQL数据库

首先,添加MySQL和Spring Data JPA的依赖:

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

然后,在 application.properties 中配置数据库连接信息:

spring.datasource.url = jdbc:mysql://localhost:3306/mydb
spring.datasource.username = root
spring.datasource.password = password
spring.jpa.database - platform = org.hibernate.dialect.MySQL5InnoDBDialect

创建一个实体类,例如 User.java

package com.example.myfirstspringbootapp;

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方法
}

@Entity 注解表示该类是一个JPA实体,@Id 注解表示该属性是实体的主键,@GeneratedValue 用于指定主键的生成策略。

创建一个Repository接口,例如 UserRepository.java

package com.example.myfirstspringbootapp;

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

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

JpaRepository 提供了一系列常用的CRUD方法。

最后,在Controller中使用Repository:

package com.example.myfirstspringbootapp;

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 UserRepository userRepository;

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

访问 http://localhost:8080/users,会返回数据库中所有用户的列表(如果有数据的话)。

6.2 访问MongoDB数据库

添加MongoDB和Spring Data MongoDB的依赖:

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

application.properties 中配置MongoDB连接信息:

spring.data.mongodb.uri = mongodb://localhost:27017/mydb

创建一个MongoDB文档类,例如 Book.java

package com.example.myfirstspringbootapp;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Book {
    @Id
    private String id;
    private String title;
    private String author;

    // 省略getter和setter方法
}

@Document 注解表示该类对应MongoDB中的一个文档。

创建一个MongoDB Repository接口,例如 BookRepository.java

package com.example.myfirstspringbootapp;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface BookRepository extends MongoRepository<Book, String> {
}

在Controller中使用Repository:

package com.example.myfirstspringbootapp;

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 BookController {
    @Autowired
    private BookRepository bookRepository;

    @GetMapping("/books")
    public List<Book> getBooks() {
        return bookRepository.findAll();
    }
}

访问 http://localhost:8080/books,会返回MongoDB中所有书籍的列表(如果有数据的话)。

7. 安全机制

Spring Boot提供了强大的安全框架Spring Security来保障应用的安全性。

7.1 添加依赖

pom.xml 中添加Spring Security依赖:

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

7.2 基本配置

Spring Security默认会对所有请求进行身份验证。启动应用后,访问任何URL,会弹出一个登录框,默认用户名是 user,密码会在启动日志中显示。

你也可以自定义用户名和密码。在 application.properties 中添加:

spring.security.user.name = admin
spring.security.user.password = secret

7.3 自定义安全配置

创建一个配置类,例如 SecurityConfig.java

package com.example.myfirstspringbootapp;

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 SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
           .authorizeRequests()
               .antMatchers("/", "/hello").permitAll()
               .anyRequest().authenticated()
               .and()
           .formLogin()
               .loginPage("/login")
               .permitAll()
               .and()
           .logout()
               .permitAll();
    }

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

configure 方法中,我们配置了对 //hello 路径的请求无需认证,其他请求需要认证。同时配置了登录页面为 /login,并允许所有用户访问登录和注销页面。passwordEncoder 方法用于配置密码编码器,这里使用BCrypt算法对密码进行加密。

8. 部署Spring Boot应用

8.1 打包成Jar文件

使用Maven的 package 命令可以将Spring Boot项目打包成一个可执行的Jar文件。在项目根目录下的命令行中执行:

mvn clean package

打包完成后,在 target 目录下会生成一个 my - first - spring - boot - app - 0.0.1 - SNAPSHOT.jar 文件(文件名根据项目实际情况可能不同)。

8.2 在服务器上运行

将生成的Jar文件上传到服务器,然后在服务器上使用以下命令运行:

java -jar my - first - spring - boot - app - 0.0.1 - SNAPSHOT.jar

如果需要在后台运行,可以使用 nohup 命令:

nohup java -jar my - first - spring - boot - app - 0.0.1 - SNAPSHOT.jar &

这样Spring Boot应用就会在服务器上运行起来,通过服务器的IP地址和配置的端口号就可以访问应用。

8.3 部署到容器(如Tomcat)

Spring Boot项目默认是一个可执行的Jar文件,也可以打包成War文件部署到传统的Servlet容器(如Tomcat)中。

首先,在 pom.xml 中修改打包方式为War:

<packaging>war</packaging>

然后,排除Spring Boot内置的Tomcat依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring - boot - starter - tomcat</artifactId>
    <scope>provided</scope>
</dependency>

接着,让Spring Boot的主类继承自 SpringBootServletInitializer 并重写 configure 方法:

package com.example.myfirstspringbootapp;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class MyFirstSpringBootAppApplication extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MyFirstSpringBootAppApplication.class);
    }
}

最后,使用 mvn clean package 命令打包项目,会在 target 目录下生成一个War文件。将War文件部署到Tomcat的 webapps 目录下,启动Tomcat即可访问应用。

通过以上步骤,你已经对Spring Boot的入门知识有了全面的了解,可以开始使用Spring Boot进行Java项目的开发。在实际开发中,还可以深入学习Spring Boot的更多高级特性,如微服务架构、分布式系统等相关内容。