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

Springboot企业级开发学习入门教程

慕盖茨4494581
关注TA
已关注
手记 262
粉丝 12
获赞 29
概述

Spring Boot是一个简化开发流程的框架,旨在通过最少的配置快速搭建企业级应用。本文将详细介绍Spring Boot企业级开发学习入门的内容,包括环境搭建、核心功能介绍、实战示例以及部署与运行等。

Spring Boot简介

Spring Boot是什么

Spring Boot 是一个基于 Spring 框架的简化开发工具,它允许开发者通过最少的配置来快速搭建独立的、生产级别的应用。Spring Boot 旨在简化 Spring 应用的初始搭建以及开发过程,通过提供默认配置来减少开发者手动配置的繁琐工作。

Spring Boot的优势

  1. 开箱即用:Spring Boot 提供了大量的默认配置,使得开发人员可以快速上手。
  2. 自动配置:通过自动配置,Spring Boot 能够自动检测应用的组件和依赖,减少了配置文件的编写。
  3. 嵌入式容器:Spring Boot 通常与嵌入式的Servlet容器(如Tomcat、Jetty)结合使用,简化了部署流程。
  4. 独立运行:支持应用以jar或war包的形式独立运行,可以方便地迁移到云环境或其他服务器。
  5. Actuator监控:包含Actuator模块,可以方便地监控应用的健康状态、性能等信息。
  6. 支持热部署:开发过程中,修改代码后不需要重启应用,可以实现热部署。
  7. 社区支持:Spring Boot 继承了 Spring 框架强大的社区支持和广泛的应用场景。

Spring Boot的开发环境搭建

环境要求

  • JDK:建议使用JDK 11 或更高版本。
  • IDE:推荐使用 IntelliJ IDEA 或 Eclipse。
  • Maven:需要安装 Maven 3.2+。

创建项目

使用 IntelliJ IDEA 创建 Spring Boot 项目:

  1. 打开 IntelliJ IDEA,选择 "File" -> "New" -> "Project"。
  2. 在 "New Project" 对话框中选择 "Spring Initializr"。
  3. 输入项目基本信息,如组名和项目名。
  4. 选择编程语言为 Java。
  5. 选择 Spring Boot 版本。
  6. 勾选所需的依赖,如 Web、Spring Data JPA、Thymeleaf 等。
  7. 点击 "Finish" 创建项目。

添加依赖

在项目的 pom.xml 文件中添加依赖,例如:

<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>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
       .<groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
</dependencies>

通过 Maven 的依赖管理,自动下载所需的库文件。

快速入门项目

创建第一个Spring Boot项目

使用 Spring Initializr 创建一个新的 Spring Boot 项目,选择 Web 和 JPA 作为依赖。创建完成后,项目的基本结构如下:

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

项目的基本结构

主启动类

主启动类通常位于 src/main/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);
    }
}

@SpringBootApplication 是一个组合注解,包含 @Configuration@EnableAutoConfiguration@ComponentScan

控制器

控制器用于处理 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;

@RestController
@RequestMapping("/api")
public class HelloController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, Spring Boot!";
    }
}

引入依赖和配置

pom.xml 文件中添加依赖,并在 application.properties 文件中配置应用属性,例如数据库连接:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.h2.console.enabled=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Spring Boot核心功能介绍

自动配置

Spring Boot 通过 @EnableAutoConfiguration 注解来提供自动配置功能。例如在 DemoApplication 类中:

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

这个注解会根据应用的依赖自动配置 Spring Bean。例如,如果项目中包含了 Web 依赖,Spring Boot 会自动配置 DispatcherServletFilterListener 等。

依赖注入

Spring Boot 使用依赖注入来管理 Bean 的创建和依赖关系。例如:

package com.example.demo.service;

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

@Service
public class HelloService {

    @Autowired
    private HelloRepository helloRepository;

    public String sayHello() {
        return helloRepository.getMessage();
    }
}

使用 @Autowired 注解将 HelloRepository 依赖注入到 HelloService 中。

静态资源处理

Spring Boot 默认会处理 /static/public/resources/templates 目录下的静态文件。例如,在 src/main/resources/static 目录下放置的 index.html 文件会直接被访问到:

<!DOCTYPE html>
<html>
<head>
    <title>Spring Boot Example</title>
</head>
<body>
    <h1>Hello, Spring Boot!</h1>
</body>
</html>

异步处理和任务调度

异步处理

通过 @Async 注解实现异步方法调用。例如:

package com.example.demo.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    @Async
    public void asyncMethod() {
        try {
            Thread.sleep(2000);
            System.out.println("异步任务执行完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

任务调度

使用 @Scheduled 注解实现定时任务。例如:

package com.example.demo.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledService {

    @Scheduled(cron = "0/5 * * * * *")
    public void scheduledTask() {
        System.out.println("任务每5秒执行一次");
    }
}
实战:开发一个简单的RESTful API

创建RESTful服务

定义 RESTful 服务接口和实现类。例如:

package com.example.demo.controller;

import com.example.demo.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping
    public List<Book> getAllBooks() {
        return bookService.getAllBooks();
    }

    @GetMapping("/{id}")
    public Book getBookById(@PathVariable("id") Long id) {
        return bookService.getBookById(id);
    }

    @PostMapping
    public Book addBook(@RequestBody Book book) {
        return bookService.addBook(book);
    }

    @PutMapping("/{id}")
    public Book updateBook(@PathVariable("id") Long id, @RequestBody Book book) {
        return bookService.updateBook(id, book);
    }

    @DeleteMapping("/{id}")
    public void deleteBook(@PathVariable("id") Long id) {
        bookService.deleteBook(id);
    }
}

使用Spring Data JPA进行数据库操作

定义实体类:

package com.example.demo.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String author;

    // 构造函数、getters和setters
    public Book() {}

    public Long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
}

定义 Repository 接口:

package com.example.demo.repository;

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

public interface BookRepository extends JpaRepository<Book, Long> {
    List<Book> findByAuthor(String author);
}

实现 Service 类:

package com.example.demo.service;

import com.example.demo.entity.Book;
import com.example.demo.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    public List<Book> getAllBooks() {
        return bookRepository.findAll();
    }

    public Book getBookById(Long id) {
        return bookRepository.findById(id).orElse(null);
    }

    public Book addBook(Book book) {
        return bookRepository.save(book);
    }

    public Book updateBook(Long id, Book book) {
        if (bookRepository.existsById(id)) {
            book.setId(id);
            return bookRepository.save(book);
        }
        return null;
    }

    public void deleteBook(Long id) {
        bookRepository.deleteById(id);
    }
}

实现分页和排序功能

在 Repository 中使用 Spring Data JPA 的分页和排序功能:

package com.example.demo.repository;

import com.example.demo.entity.Book;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Long> {
    Page<Book> findByAuthor(String author, Pageable pageable);
}

在 Service 中调用分页方法:

public Page<Book> getBooksByAuthor(String author, Pageable pageable) {
    return bookRepository.findByAuthor(author, pageable);
}
日志管理和异常处理

Logback日志配置

resources 目录下创建 logback-spring.xml 文件,配置 Logback 日志:

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

异常处理机制

Spring Boot 提供了全局异常处理机制。例如:

package com.example.demo.exception;

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

@ControllerAdvice
public class GlobalExceptionHandler {

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

自定义异常处理

定义自定义异常类:

package com.example.demo.exception;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class BookNotFoundException extends RuntimeException {
    public BookNotFoundException(String message) {
        super(message);
    }
}

在 Service 中抛出自定义异常:

public Book getBookById(Long id) {
    Book book = bookRepository.findById(id).orElse(null);
    if (book == null) {
        throw new BookNotFoundException("Book not found with id " + id);
    }
    return book;
}
部署与运行

打包与发布

可以使用 Maven 打包 Spring Boot 应用:

mvn clean package

生成的 jar 文件可以在 target 目录下找到。使用以下命令运行 jar 文件:

java -jar target/demo-0.0.1-SNAPSHOT.jar

部署到Tomcat和Docker

部署到Tomcat

可以将 Spring Boot 应用打包为 war 文件并部署到 Tomcat 服务器。修改 pom.xml 文件,添加 war 打包插件:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.2.2</version>
        </plugin>
    </plugins>
</build>

修改 pom.xml 配置为 war 打包:

<packaging>war</packaging>

生成 war 文件:

mvn clean package

将生成的 war 文件部署到 Tomcat 服务器。

部署到Docker

创建 Dockerfile 文件:

FROM openjdk:11-jre-slim
COPY target/demo-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]

构建并运行 Docker 容器:

docker build -t springboot-demo .
docker run -p 8080:8080 springboot-demo

监控与调优

Spring Boot 提供了 Actuator 模块来监控应用健康状态和性能指标。在 pom.xml 文件中添加 Actuator 依赖:

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

配置 Actuator 端点,并在 application.properties 文件中启用需要的端点:

management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always

访问 /actuator 端点查看应用的健康状态和性能指标。

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