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

Springboot项目开发入门教程

慕容森
关注TA
已关注
手记 410
粉丝 183
获赞 651
概述

Spring Boot 是一个用于简化 Spring 应用开发的框架,通过自动配置和约定优于配置的方式,快速构建 Java 应用程序。本文将详细介绍 Spring Boot 项目开发的环境搭建、核心概念与配置、常用功能实现、测试与部署以及调试与日志管理,帮助开发者更好地理解和使用 Spring Boot 项目开发。

Spring Boot 简介

Spring Boot 是由 Spring 团队开发的一个用于简化 Spring 应用初始搭建及开发过程的框架。它通过约定优于配置的方式,自动配置各种常见场景,从而快速构建 Java 应用程序。Spring Boot 的核心目标是简化 Spring 应用的开发、部署和运行。

Spring Boot是什么

Spring Boot 是 Spring 项目的子项目,旨在简化新 Spring 应用的初始搭建以及开发过程。Spring Boot 通过提供默认配置并自动配置常见场景,使开发者能够专注于应用的业务逻辑,而无需过多关注基础设施和技术栈的配置细节。

Spring Boot的优势

Spring Boot 的主要优势包括:

  1. 开箱即用:提供了一系列默认配置,使得开发人员可以快速构建应用。
  2. 自动配置:基于约定将配置自动应用到应用中,减少了配置文件的工作量。
  3. Spring 生态系统集成:简化了 Spring 生态系统中的众多子项目的集成和使用。
  4. 无需 XML 配置:大多数情况下,可以通过注解和属性配置来代替传统的 XML 配置。
  5. 独立的可执行 JAR 文件:应用可以打包成独立的可执行 JAR 文件,便于部署和运行。
  6. 嵌入式 Web 服务器:内置了多种嵌入式的 Web 服务器,如 Tomcat、Jetty 和 Undertow,简化部署。
  7. 全面的依赖管理:通过 Maven 或 Gradle 插件自动处理依赖管理。
开发环境搭建

安装 Java

确保已经安装了 Java 开发工具包 (JDK),推荐使用 Java 8 或更高版本。

java -version

安装 Maven 或 Gradle

Maven 或 Gradle 用于构建和管理项目的依赖。

mvn --version

gradle --version

安装 IDE

推荐使用 IntelliJ IDEA 或 Eclipse。以下是安装步骤:

# IntelliJ IDEA 安装步骤
# 下载 IntelliJ IDEA 并安装
# 打开 IntelliJ IDEA

安装 Spring Initializr

Spring Initializr 是一个在线工具,用于快速生成 Spring Boot 项目的骨架。

# 访问 Spring Initializr 网站
# https://start.spring.io/
# 生成项目代码并下载
创建Spring Boot项目
使用Spring Initializr创建项目

Spring Initializr 提供了一个在线的项目生成工具,可以通过浏览器快速创建 Spring Boot 项目的骨架。

步骤

  1. 访问 Spring Initializr 网站:https://start.spring.io/
  2. 选择项目类型:
    • Spring Boot 版本
    • 项目包名
    • 依赖模块
  3. 下载项目压缩包
  4. 解压项目压缩包到本地开发目录下
  5. 使用 Maven 或 Gradle 构建工具启动项目
    # 解压后,使用 Maven 构建项目
    mvn clean install
    # 或者使用 Gradle 构建项目
    gradle build
手动创建Spring Boot项目

手动创建 Spring Boot 项目需要手动编写项目结构和依赖配置。

步骤

  1. 创建 Maven 或 Gradle 项目
  2. 初始化项目目录结构
  3. 添加 pom.xmlbuild.gradle 文件
  4. 配置 Spring Boot 依赖

1. 创建项目目录结构

创建如下目录结构:

src
└── main
    ├── java
    │   └── com
    │       └── example
    │           └── demo
    │               ├── DemoApplication.java
    │               └── controller
    │                   └── HelloController.java
    └── resources
        └── application.properties

2. 创建 pom.xml

配置 Maven 项目依赖和插件。

<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.7.0</version>
    </parent>
    <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>
        </plugins>
    </build>
</project>

3. 创建 application.properties

配置文件用于定义应用的属性。

# application.properties
server.port=8080

4. 创建 DemoApplication.java

启动类用于启动 Spring Boot 应用。

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

5. 创建 HelloController.java

控制器用于处理 HTTP 请求。

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

使用 Gradle 创建项目

创建 build.gradle 文件。

plugins {
    id 'org.springframework.boot' version '2.7.0'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
}
核心概念与配置
Spring Boot的核心注解

Spring Boot 中常用的一些核心注解包括:

  • @SpringBootApplication:用于标记主类,表示这是一个 Spring Boot 应用。
  • @Configuration:定义配置类,通常与 @Bean 注解结合使用。
  • @ComponentScan:扫描指定路径下定义的 Bean。
  • @EnableAutoConfiguration:自动配置应用,根据类路径中的 jar 依赖推断需要配置的内容。
  • @EnableJpaRepositories:配置 JPA 库的自动扫描和注册。
  • @EnableWebMvc:启用 Spring MVC 配置。

示例代码

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);
    }
}
应用配置文件

Spring Boot 提供了多种配置文件,如 application.propertiesapplication.yml,用于定义应用的属性和配置。

application.properties

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=root

application.yml

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/demo
    username: root
    password: root
自动配置机制

Spring Boot 使用自动配置机制来简化配置过程。自动配置通过 @EnableAutoConfiguration 注解启用,它会根据类路径中的 jar 依赖推断需要配置的内容,并自动配置 Spring 应用。

示例代码

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);
    }
}
常用功能实现
RESTful API开发

Spring Boot 中使用 @RestController 注解定义 RESTful API 控制器,处理 HTTP 请求。

示例代码

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!";
    }
}
数据库集成(JPA、MyBatis等)

JPA集成

使用 Spring Boot 和 JPA 可以轻松实现数据库操作。

配置 pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

配置 application.properties

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update

定义实体类

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.AUTO)
    private Long id;
    private String name;
    private String email;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

定义 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;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

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

定义 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.*;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

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

MyBatis集成

集成 MyBatis 需要添加 MyBatis 相关依赖。

配置 pom.xml

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
</dependency>

配置 application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/demo
spring.datasource.username=root
spring.datasource.password=root

定义 Mapper 接口

package com.example.demo.mapper;

import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper {
    void insert(User user);
}

定义 Mapper XML 文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.mapper.UserMapper">
    <insert id="insert">
        INSERT INTO user (name, email) VALUES (#{name}, #{email})
    </insert>
</mapper>

定义 Service 类

package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public void save(User user) {
        userMapper.insert(user);
    }
}

定义 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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/save")
    public User saveUser(@RequestBody User user) {
        userService.save(user);
        return user;
    }
}
安全认证(Spring Security)

使用 Spring Security 进行安全认证,保护应用不受未授权访问。

配置 pom.xml

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

配置 SecurityConfig.java

package com.example.demo.config;

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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class SecurityConfig 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();
    }

    @Override
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build();

        return new InMemoryUserDetailsManager(user);
    }
}

示例 Controller

package com.example.demo.controller;

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

@Controller
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "home";
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }
}
测试与部署
单元测试与集成测试

使用 JUnit 和 Spring Boot Test 框架进行单元测试和集成测试。

配置 pom.xml

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

示例单元测试代码

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class DemoApplicationTests {
    @Autowired
    private UserService userService;

    @Test
    public void contextLoads() {
        User user = new User();
        user.setName("test");
        user.setEmail("test@test.com");
        userService.save(user);
    }
}

示例集成测试代码

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;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {
    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void testSaveUser() {
        User user = new User();
        user.setName("test");
        user.setEmail("test@test.com");
        ResponseEntity<User> response = restTemplate.postForEntity("/users/save", user, User.class);
        assert response.getStatusCode().is2xxSuccessful();
    }
}
应用打包与部署

使用 Maven 或 Gradle 打包应用,并部署到服务器上。

使用 Maven 打包

mvn clean package

使用 Gradle 打包

gradle build

打包结果

打包后会在 targetbuild 目录下生成一个 .jar 文件,例如 demo-0.0.1-SNAPSHOT.jar

部署到服务器

将生成的 .jar 文件复制到服务器上,并使用 Java 命令运行:

java -jar demo-0.0.1-SNAPSHOT.jar
部署到云平台(如Docker)

使用 Docker 部署 Spring Boot 应用。

创建 Dockerfile

FROM openjdk:8-jdk-alpine
VOLUME /tmp
ARG JAR_FILE
ADD ${JAR_FILE} app.jar
ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-jar","/app.jar"]

编译并构建 Docker 镜像

mvn package -DskipTests
docker build -t my-spring-boot-app .

运行 Docker 容器

docker run -p 8080:8080 my-spring-boot-app
调试与日志
常见问题排查

常见问题包括启动失败、配置错误等。

启动失败

# 查看日志输出
java -jar demo-0.0.1-SNAPSHOT.jar > log.txt 2>&1
tail -f log.txt

配置错误

检查配置文件中的属性和配置。

日志配置与管理

Spring Boot 默认使用 Logback 进行日志记录,可以通过 application.propertiesapplication.yml 配置日志属性。

配置 application.properties

logging.level.root=INFO
logging.file.name=app.log

配置 application.yml

logging:
  level:
    root: INFO
  file:
    name: app.log
性能监控

使用 Actuator 端点监控应用状态。

配置依赖

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

访问监控端点

访问 http://localhost:8080/actuator 查看监控信息。

配置安全

management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always

通过这些配置,可以方便地监控应用的状态和性能,以及进行故障排除。

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