Springboot單體架構搭建入門教程
標簽:
SpringBoot
概述
本文介绍了如何从零开始搭建Spring Boot单体架构,涵盖了环境搭建、项目配置、模块开发以及部署运维的全过程,帮助读者快速入门Spring Boot单体架构搭建。
Spring Boot简介 Spring Boot是什么Spring Boot是Spring框架的一个子项目,旨在简化Spring应用的初始搭建及配置过程,使开发者能够快速构建独立的、生产级别的基于Spring的应用程序。Spring Boot通过约定优于配置的原则,尽可能减少配置,使得开发者可以更专注于业务逻辑,而不是复杂的配置。
Spring Boot的特点与优势- 自动配置:Spring Boot通过约定优于配置的原则,自动配置Spring应用,大大减少了配置文件的数量和复杂度。
- 独立运行:Spring Boot应用可以打包为可执行的JAR或WAR文件,自带嵌入式的Tomcat、Jetty或Undertow服务器,可以在任何地方独立运行。
- 嵌入式容器选择:可选择嵌入Tomcat、Jetty、Undertow作为轻量级容器。
- 全面的自动化配置:内置了对各种技术的支持,只需添加相应的依赖,Spring Boot会自动配置相应的功能。
- 内建的特性:包括内建的AOP、Web开发、缓存、数据库连接管理等。
- 生产就绪特性:包括内置的指标、健康检查、外部配置等,使应用更加健壮。
- 无代码生成:不需要使用额外的代码生成工具或XML配置,简化了开发流程。
- 开箱即用:提供了大量的启动器(starters),简化了依赖管理,方便开发者快速构建应用。
- 快速故障排除:内建的健康检查工具,帮助开发者快速定位问题。
- 自动化配置:Spring Boot继承了Spring框架的功能,但提供了更高级的自动化配置功能。传统Spring需要手动配置bean、数据源、事务管理器等,而Spring Boot则通过约定优于配置的原则自动配置这些内容。
- 嵌入式容器:传统Spring通常需要与Tomcat、Jetty等外部服务器结合使用,而Spring Boot自带嵌入式Tomcat、Jetty或Undertow服务器,简化了开发流程。
- 配置简化:传统Spring应用通常需要大量的XML配置文件,而Spring Boot通过约定优于配置的原则,使用少量的配置即可启动应用。
- 依赖管理:Spring Boot提供了大量的启动器(starters),简化了依赖管理,使得项目依赖更加清晰。而传统Spring需要手动添加和管理依赖。
示例代码
// 一个简单的Spring Boot应用主类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
环境搭建
开发工具选择与安装
通常使用以下工具来开发Spring Boot应用:
- IDEA:专业的Java开发环境,提供大量的插件和功能,支持Spring Boot项目搭建。
- Eclipse:另一款流行的Java开发环境,适合初学者使用。
- Spring Tool Suite (STS):基于Eclipse的一款IDE,专门为Spring开发者设计。
- Visual Studio Code (VS Code):轻量级代码编辑器,通过插件也可以支持Spring Boot开发。
示例代码
// 这里做了一个简单的IDEA配置示范
// 在IDEA中创建Spring Boot项目
// 1. 打开File -> New -> Project
// 2. 选择Spring Initializr
// 3. 选择所需的技术栈,如Spring Web
// 4. 填写项目名称和位置
JDK环境配置
Spring Boot需要Java 8及以上版本。确保安装了最新版本的JDK,并配置好JDK环境变量。
示例代码
// 设置JDK环境变量
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
export PATH=$JAVA_HOME/bin:$PATH
Maven或Gradle配置
Maven配置
- 创建
pom.xml
文件:在项目根目录下创建pom.xml
文件,用于管理项目依赖。 - 添加依赖:在
pom.xml
中添加Spring Boot的依赖。 - 配置插件:可以使用
spring-boot-maven-plugin
插件构建可执行的JAR文件。
示例代码
<!-- 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>
<packaging>jar</packaging>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Gradle配置
- 创建
build.gradle
文件:在项目根目录下创建build.gradle
文件,用于管理项目依赖。 - 添加依赖:在
build.gradle
中添加Spring Boot的依赖。 - 配置插件:使用
spring-boot
插件构建可执行的JAR文件。
示例代码
// 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'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
创建第一个Spring Boot项目
- 创建项目:在IDE中创建一个新的Spring Boot项目。
- 添加依赖:选择所需的依赖,如Spring Web。
- 编写代码:编写简单的Hello World应用。
示例代码
// Application.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
// HelloController.java
package com.example.demo;
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!";
}
}
项目基本结构与配置
项目目录结构介绍
一个典型的Spring Boot项目结构如下:
src/main/java
:存放Java源代码。src/main/resources
:存放静态资源、配置文件等。src/test/java
:存放单元测试代码。src/test/resources
:存放单元测试资源文件。pom.xml
或build.gradle
:项目构建配置文件。application.properties
或application.yml
:Spring Boot配置文件。
示例代码
// Application.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
配置文件详解
Spring Boot支持两种配置文件格式:application.properties
和application.yml
。以下是常用的配置项:
application.properties
# 端口配置
server.port=8080
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
# 日志配置
logging.level.root=INFO
logging.file.name=log.txt
application.yml
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
logging:
level:
root: INFO
file:
name: log.txt
主启动类编写
主启动类是Spring Boot应用的入口点。使用@SpringBootApplication
注解,该注解是一个组合注解,包含了@Configuration
、@EnableAutoConfiguration
和@ComponentScan
。
示例代码
// Application.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
常用模块开发
RESTful API的开发
示例代码
// HelloController.java
package com.example.demo;
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!";
}
}
数据库访问与JPA的使用
示例代码
// User.java
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.AUTO)
private Long id;
private String name;
private String email;
// getter and setter
}
// UserRepository.java
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
// UserService.java
package com.example.demo;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.demo.UserRepository;
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Iterable<User> getUsers() {
return userRepository.findAll();
}
}
// UserController.java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.UserService;
@RestController
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/users")
public Iterable<User> getUsers() {
return userService.getUsers();
}
}
示例代码
// application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
日志配置与使用
示例代码
# application.properties
logging.level.root=INFO
logging.file.name=log.txt
示例代码
// LogService.java
package com.example.demo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
@Service
public class LogService {
private static final Logger logger = LogManager.getLogger(LogService.class);
public void logInfo(String message) {
logger.info(message);
}
}
服务监控与健康检查
示例代码
// HealthCheckService.java
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class HealthCheckService {
public boolean isHealthy() {
// 检查数据库连接、缓存等
return true;
}
}
// HealthCheckController.java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.demo.HealthCheckService;
@RestController
public class HealthCheckController {
@Autowired
private HealthCheckService healthCheckService;
@GetMapping("/health")
public ResponseEntity<String> healthCheck() {
return ResponseEntity.ok("OK");
}
}
搭建单体应用
单体架构的概念与特点
单体架构是一种将所有功能模块打包在一起的软件架构。其特点包括:
- 单一部署:所有功能模块部署在一起,便于管理和维护。
- 共享资源:所有模块共享相同的数据库、缓存等资源。
- 易于开发:初期开发和测试简单,适合小规模应用。
- 扩展性有限:难以扩展和维护,当应用规模变大时,维护成本增加。
示例代码
// Application.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
示例代码
// HelloController.java
package com.example.demo;
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!";
}
}
服务整合与部署
示例代码
// User.java
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.AUTO)
private Long id;
private String name;
private String email;
// getter and setter
}
// UserRepository.java
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
// UserService.java
package com.example.demo;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.demo.UserRepository;
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Iterable<User> getUsers() {
return userRepository.findAll();
}
}
// UserController.java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.UserService;
@RestController
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/users")
public Iterable<User> getUsers() {
return userService.getUsers();
}
}
示例代码
// application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
常见问题及解决方案
常见错误与异常处理
示例代码
// HelloController.java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@RestController
public class HelloController {
@GetMapping("/hello")
public ResponseEntity<String> hello() {
return new ResponseEntity<>("Hello, Spring Boot!", HttpStatus.OK);
}
}
性能优化与调试技巧
示例代码
# application.properties
spring.profiles.active=prod
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.hibernate.ddl-auto=update
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.maximum-pool-size=15
项目部署与运维建议
示例代码
# 打包命令
mvn clean package
# 运行命令
java -jar target/demo-0.0.1-SNAPSHOT.jar
示例代码
# docker-compose.yml
version: '3'
services:
web:
build: .
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=prod
volumes:
- ./:/app
command: java -jar /app/target/demo-0.0.1-SNAPSHOT.jar
示例代码
# 部署到Kubernetes
kubectl apply -f deployment.yaml
示例代码
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: demo
spec:
replicas: 1
selector:
matchLabels:
app: demo
template:
metadata:
labels:
app: demo
spec:
containers:
- name: demo
image: localhost:5000/demo:v1
ports:
- containerPort: 8080
env:
- name: SPRING_PROFILES_ACTIVE
value: "prod"
示例代码
# service.yaml
apiVersion: v1
kind: Service
metadata:
name: demo-service
spec:
selector:
app: demo
ports:
- protocol: TCP
port: 8080
targetPort: 8080
type: LoadBalancer
通过以上步骤,可以成功搭建一个Spring Boot单体应用,并进行基本的开发、配置、部署和运维。
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦