第一章 第三节:Java开发环境配置
引言
在前两节中,我们深入了解了MCP协议的核心概念以及Cursor IDE与MCP的深度集成。现在,让我们将注意力转向实际的环境配置。一个完善的Java开发环境是充分发挥MCP和Cursor IDE强大功能的基础。本节将详细介绍如何从零开始配置一个现代化的Java开发环境,为后续的实战开发奠定坚实基础。
开发环境架构概览
整体架构设计
scss
┌─────────────────────────────────────────────────────────────┐
│ Java开发环境架构 │
├─────────────────────────────────────────────────────────────┤
│ Application Layer (应用层) │
│ ├── Cursor IDE (代码编辑器) │
│ ├── MCP Client (MCP客户端) │
│ └── Browser (浏览器) │
├─────────────────────────────────────────────────────────────┤
│ Development Tools Layer (开发工具层) │
│ ├── JDK (Java开发工具包) │
│ ├── Maven/Gradle (构建工具) │
│ ├── Git (版本控制) │
│ └── Docker (容器化) │
├─────────────────────────────────────────────────────────────┤
│ Runtime Environment Layer (运行时环境层) │
│ ├── JVM (Java虚拟机) │
│ ├── Spring Boot (应用框架) │
│ ├── Nacos (服务注册中心) │
│ └── MySQL/Redis (数据存储) │
├─────────────────────────────────────────────────────────────┤
│ System Layer (系统层) │
│ ├── Windows/macOS/Linux (操作系统) │
│ ├── Network (网络环境) │
│ └── Hardware (硬件资源) │
└─────────────────────────────────────────────────────────────┘
环境配置原则
1. 版本兼容性
- JDK版本:推荐使用JDK 17或21(LTS版本)
- Maven版本:3.8.0以上
- Gradle版本:7.0以上
- Spring Boot版本:3.x系列
2. 工具链统一
- 使用统一的构建工具(Maven或Gradle)
- 统一的代码格式化工具
- 统一的静态代码分析工具
- 统一的测试框架
3. 环境隔离
- 开发环境、测试环境、生产环境分离
- 使用Docker进行环境隔离
- 配置文件外部化管理
JDK安装与配置
1. JDK版本选择
版本对比分析
| 版本 | 发布时间 | LTS | 主要特性 | 推荐场景 |
|---|---|---|---|---|
| JDK 8 | 2014年 | ✅ | Lambda表达式、Stream API | 传统企业项目 |
| JDK 11 | 2018年 | ✅ | 模块系统、HTTP Client | 现代企业应用 |
| JDK 17 | 2021年 | ✅ | 密封类、模式匹配 | 新项目首选 |
| JDK 21 | 2023年 | ✅ | 虚拟线程、字符串模板 | 前沿技术探索 |
推荐配置
bash
# 推荐使用JDK 17作为主要开发版本
# 同时安装JDK 21用于新特性探索
# 检查当前Java版本
java -version
javac -version
# 预期输出
# openjdk version "17.0.9" 2023-10-17
# OpenJDK Runtime Environment (build 17.0.9+9-Ubuntu-120.04.1)
# OpenJDK 64-Bit Server VM (build 17.0.9+9-Ubuntu-120.04.1, mixed mode, sharing)
2. 多版本JDK管理
使用SDKMAN管理JDK版本
bash
# 安装SDKMAN
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
# 查看可用的JDK版本
sdk list java
# 安装JDK 17
sdk install java 17.0.9-tem
# 安装JDK 21
sdk install java 21.0.1-tem
# 切换JDK版本
sdk use java 17.0.9-tem
# 设置默认版本
sdk default java 17.0.9-tem
Windows环境配置
powershell
# 使用Chocolatey安装JDK
# 安装Chocolatey(如果未安装)
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
# 安装JDK 17
choco install openjdk17
# 安装JDK 21
choco install openjdk21
# 设置环境变量
[Environment]::SetEnvironmentVariable("JAVA_HOME", "C:\Program Files\Eclipse Adoptium\jdk-17.0.9.9-hotspot\", "Machine")
[Environment]::SetEnvironmentVariable("PATH", $env:PATH + ";$env:JAVA_HOME\bin", "Machine")
3. JVM参数优化
开发环境JVM参数
bash
# 开发环境JVM参数配置
export JAVA_OPTS="-Xms512m -Xmx2g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:+UseStringDeduplication -XX:+OptimizeStringConcat -Dfile.encoding=UTF-8 -Duser.timezone=Asia/Shanghai"
# 详细参数说明
# -Xms512m: 初始堆内存大小
# -Xmx2g: 最大堆内存大小
# -XX:+UseG1GC: 使用G1垃圾收集器
# -XX:MaxGCPauseMillis=200: 最大GC暂停时间
# -XX:+UseStringDeduplication: 字符串去重
# -XX:+OptimizeStringConcat: 字符串连接优化
# -Dfile.encoding=UTF-8: 文件编码
# -Duser.timezone=Asia/Shanghai: 时区设置
生产环境JVM参数
bash
# 生产环境JVM参数配置
export JAVA_OPTS="-Xms2g -Xmx8g -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -XX:+UseStringDeduplication -XX:+OptimizeStringConcat -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/logs/heapdump.hprof -Dfile.encoding=UTF-8 -Duser.timezone=Asia/Shanghai -Dspring.profiles.active=prod"
# 生产环境额外参数
# -XX:+HeapDumpOnOutOfMemoryError: OOM时生成堆转储
# -XX:HeapDumpPath: 堆转储文件路径
# -Dspring.profiles.active=prod: 激活生产环境配置
Maven配置与优化
1. Maven安装与配置
安装Maven
bash
# 使用SDKMAN安装Maven
sdk install maven 3.9.6
# 或者手动安装
wget https://archive.apache.org/dist/maven/maven-3/3.9.6/binaries/apache-maven-3.9.6-bin.tar.gz
tar -xzf apache-maven-3.9.6-bin.tar.gz
sudo mv apache-maven-3.9.6 /opt/maven
# 设置环境变量
export MAVEN_HOME=/opt/maven
export PATH=$PATH:$MAVEN_HOME/bin
Maven配置文件
xml
<!-- ~/.m2/settings.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<!-- 本地仓库路径 -->
<localRepository>${user.home}/.m2/repository</localRepository>
<!-- 服务器认证信息 -->
<servers>
<server>
<id>nexus</id>
<username>admin</username>
<password>admin123</password>
</server>
</servers>
<!-- 镜像配置 -->
<mirrors>
<mirror>
<id>aliyun</id>
<name>Aliyun Maven</name>
<url>https://maven.aliyun.com/repository/public</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
<!-- 配置文件 -->
<profiles>
<profile>
<id>jdk-17</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>17</jdk>
</activation>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.compilerVersion>17</maven.compiler.compilerVersion>
</properties>
</profile>
</profiles>
<!-- 激活的配置文件 -->
<activeProfiles>
<activeProfile>jdk-17</activeProfile>
</activeProfiles>
</settings>
2. Maven项目配置
父POM配置
xml
<!-- pom.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<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>user-management-system</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<name>User Management System</name>
<description>基于Spring Boot和Nacos的用户管理系统</description>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 版本管理 -->
<spring-boot.version>3.2.0</spring-boot.version>
<spring-cloud.version>2023.0.0</spring-cloud.version>
<spring-cloud-alibaba.version>2022.0.0.0</spring-cloud-alibaba.version>
<nacos.version>2.3.0</nacos.version>
<mysql.version>8.0.33</mysql.version>
<mybatis-plus.version>3.5.4</mybatis-plus.version>
<druid.version>1.2.20</druid.version>
<lombok.version>1.18.30</lombok.version>
<mapstruct.version>1.5.5.Final</mapstruct.version>
<junit.version>5.10.0</junit.version>
<mockito.version>5.6.0</mockito.version>
</properties>
<modules>
<module>user-service</module>
<module>order-service</module>
<module>payment-service</module>
<module>common</module>
</modules>
<dependencyManagement>
<dependencies>
<!-- Spring Boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud Alibaba -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- 数据库相关 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- 工具类 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${mapstruct.version}</version>
</dependency>
<!-- 测试相关 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<!-- Spring Boot Maven Plugin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<!-- Maven Compiler Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>17</source>
<target>17</target>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<!-- Maven Surefire Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<includes>
<include>**/*Test.java</include>
<include>**/*Tests.java</include>
</includes>
</configuration>
</plugin>
<!-- Maven Failsafe Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<includes>
<include>**/*IT.java</include>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<profiles>
<profile>
<id>dev</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<spring.profiles.active>test</spring.profiles.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<spring.profiles.active>prod</spring.profiles.active>
</properties>
</profile>
</profiles>
</project>
3. Maven插件配置
代码质量插件
xml
<!-- 在pom.xml中添加代码质量插件 -->
<build>
<plugins>
<!-- Checkstyle Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.3.1</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<linkXRef>false</linkXRef>
</configuration>
<executions>
<execution>
<id>validate</id>
<phase>validate</phase>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- SpotBugs Plugin -->
<plugin>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-maven-plugin</artifactId>
<version>4.7.3.6</version>
<configuration>
<effort>Max</effort>
<threshold>Low</threshold>
<xmlOutput>true</xmlOutput>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- JaCoCo Plugin -->
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.10</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Gradle配置与优化
1. Gradle安装与配置
安装Gradle
bash
# 使用SDKMAN安装Gradle
sdk install gradle 8.5
# 或者使用包管理器
# Ubuntu/Debian
sudo apt install gradle
# macOS
brew install gradle
# Windows
choco install gradle
Gradle配置文件
properties
# gradle.properties
# 项目配置
org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.daemon=true
# 编码配置
systemProp.file.encoding=UTF-8
systemProp.user.timezone=Asia/Shanghai
# 构建配置
org.gradle.configureondemand=true
org.gradle.workers.max=4
2. Gradle项目配置
父项目build.gradle
gradle
// build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.0'
id 'io.spring.dependency-management' version '1.1.4'
id 'checkstyle'
id 'pmd'
id 'jacoco'
}
group = 'com.example'
version = '1.0.0'
sourceCompatibility = '17'
repositories {
mavenCentral()
maven { url 'https://maven.aliyun.com/repository/public' }
}
ext {
set('springCloudVersion', "2023.0.0")
set('springCloudAlibabaVersion', "2022.0.0.0")
set('nacosVersion', "2.3.0")
set('mysqlVersion', "8.0.33")
set('mybatisPlusVersion', "3.5.4")
set('druidVersion', "1.2.20")
set('lombokVersion', "1.18.30")
set('mapstructVersion', "1.5.5.Final")
set('junitVersion', "5.10.0")
set('mockitoVersion', "5.6.0")
}
dependencies {
// Spring Boot
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-actuator'
// Spring Cloud
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
implementation 'org.springframework.cloud:spring-cloud-starter-loadbalancer'
// Spring Cloud Alibaba
implementation 'com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery'
implementation 'com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-config'
// 数据库
implementation "mysql:mysql-connector-java:${mysqlVersion}"
implementation "com.baomidou:mybatis-plus-boot-starter:${mybatisPlusVersion}"
implementation "com.alibaba:druid-spring-boot-starter:${druidVersion}"
// 工具类
compileOnly "org.projectlombok:lombok:${lombokVersion}"
annotationProcessor "org.projectlombok:lombok:${lombokVersion}"
implementation "org.mapstruct:mapstruct:${mapstructVersion}"
annotationProcessor "org.mapstruct:mapstruct-processor:${mapstructVersion}"
// 测试
testImplementation "org.springframework.boot:spring-boot-starter-test"
testImplementation "org.junit.jupiter:junit-jupiter:${junitVersion}"
testImplementation "org.mockito:mockito-core:${mockitoVersion}"
}
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
mavenBom "com.alibaba.cloud:spring-cloud-alibaba-dependencies:${springCloudAlibabaVersion}"
}
}
// 代码质量配置
checkstyle {
toolVersion = '10.12.4'
configFile = file('checkstyle.xml')
ignoreFailures = false
}
pmd {
toolVersion = '6.55.0'
ruleSetFiles = files('pmd-ruleset.xml')
ignoreFailures = false
}
jacoco {
toolVersion = '0.8.10'
}
jacocoTestReport {
reports {
xml.required = true
html.required = true
}
}
jacocoTestCoverageVerification {
violationRules {
rule {
limit {
minimum = 0.80
}
}
}
}
// 测试配置
test {
useJUnitPlatform()
finalizedBy jacocoTestReport
finalizedBy jacocoTestCoverageVerification
}
// 构建配置
build {
dependsOn check
dependsOn jacocoTestReport
}
IDE插件安装与配置
1. Cursor IDE插件推荐
必装插件
json
// .cursor/extensions.json
{
"recommendations": [
// Java开发
"redhat.java",
"vscjava.vscode-java-debug",
"vscjava.vscode-java-test",
"vscjava.vscode-maven",
"vscjava.vscode-gradle",
// Spring Boot
"vmware.vscode-spring-boot",
"pivotal.vscode-spring-boot-dashboard",
// 代码质量
"sonarsource.sonarlint-vscode",
"ms-vscode.vscode-json",
// 数据库
"ms-mssql.mssql",
"mtxr.sqltools",
"mtxr.sqltools-driver-mysql",
// 工具
"ms-vscode.vscode-docker",
"ms-kubernetes-tools.vscode-kubernetes-tools",
"ms-vscode-remote.remote-containers",
// Git
"eamodio.gitlens",
"mhutchie.git-graph",
// 其他
"ms-vscode.vscode-yaml",
"redhat.vscode-xml",
"ms-vscode.vscode-markdown"
]
}
插件配置
json
// .cursor/settings.json
{
// Java配置
"java.configuration.updateBuildConfiguration": "automatic",
"java.compile.nullAnalysis.mode": "automatic",
"java.format.settings.url": "https://raw.githubusercontent.com/google/styleguide/gh-pages/eclipse-java-google-style.xml",
"java.format.settings.profile": "GoogleStyle",
// Spring Boot配置
"spring-boot.ls.java.home": "/usr/lib/jvm/java-17-openjdk",
"spring-boot.ls.java.vmargs": "-Xmx1024m",
// 代码质量配置
"sonarlint.connectedMode.servers": [
{
"serverId": "sonarqube",
"serverUrl": "http://localhost:9000",
"token": "your-token"
}
],
// 数据库配置
"sqltools.connections": [
{
"name": "MySQL Local",
"driver": "MySQL",
"server": "localhost",
"port": 3306,
"database": "userdb",
"username": "root",
"password": "password"
}
],
// Git配置
"gitlens.codeLens.enabled": true,
"gitlens.currentLine.enabled": true,
"gitlens.hovers.currentLine.over": "line",
// 编辑器配置
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true,
"source.fixAll": true
},
// 文件配置
"files.autoSave": "afterDelay",
"files.autoSaveDelay": 1000,
"files.encoding": "utf8",
"files.eol": "\n"
}
2. 代码格式化配置
Checkstyle配置
xml
<!-- checkstyle.xml -->
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="charset" value="UTF-8"/>
<property name="severity" value="warning"/>
<property name="fileExtensions" value="java, properties, xml"/>
<!-- 排除文件 -->
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<!-- 文件长度检查 -->
<module name="FileLength">
<property name="max" value="2000"/>
</module>
<!-- 行长度检查 -->
<module name="LineLength">
<property name="fileExtensions" value="java"/>
<property name="max" value="120"/>
</module>
<!-- 树形检查器 -->
<module name="TreeWalker">
<!-- 导入检查 -->
<module name="AvoidStarImport"/>
<module name="IllegalImport"/>
<module name="RedundantImport"/>
<module name="UnusedImports"/>
<!-- 命名检查 -->
<module name="ConstantName"/>
<module name="LocalFinalVariableName"/>
<module name="LocalVariableName"/>
<module name="MemberName"/>
<module name="MethodName"/>
<module name="PackageName"/>
<module name="ParameterName"/>
<module name="StaticVariableName"/>
<module name="TypeName"/>
<!-- 长度检查 -->
<module name="MethodLength">
<property name="max" value="150"/>
</module>
<module name="ParameterNumber">
<property name="max" value="7"/>
</module>
<!-- 空白检查 -->
<module name="EmptyForIteratorPad"/>
<module name="GenericWhitespace"/>
<module name="MethodParamPad"/>
<module name="NoWhitespaceAfter"/>
<module name="NoWhitespaceBefore"/>
<module name="OperatorWrap"/>
<module name="ParenPad"/>
<module name="TypecastParenPad"/>
<module name="WhitespaceAfter"/>
<module name="WhitespaceAround"/>
<!-- 修饰符检查 -->
<module name="ModifierOrder"/>
<module name="RedundantModifier"/>
<!-- 块检查 -->
<module name="AvoidNestedBlocks"/>
<module name="EmptyBlock"/>
<module name="LeftCurly"/>
<module name="NeedBraces"/>
<module name="RightCurly"/>
<!-- 常见编码问题 -->
<module name="EmptyStatement"/>
<module name="EqualsHashCode"/>
<module name="HiddenField"/>
<module name="IllegalInstantiation"/>
<module name="InnerAssignment"/>
<module name="MagicNumber"/>
<module name="MissingSwitchDefault"/>
<module name="MultipleVariableDeclarations"/>
<module name="SimplifyBooleanExpression"/>
<module name="SimplifyBooleanReturn"/>
<!-- 类设计检查 -->
<module name="DesignForExtension"/>
<module name="FinalClass"/>
<module name="HideUtilityClassConstructor"/>
<module name="InterfaceIsType"/>
<module name="VisibilityModifier"/>
<!-- 杂项检查 -->
<module name="ArrayTypeStyle"/>
<module name="FinalParameters"/>
<module name="TodoComment"/>
<module name="UpperEll"/>
</module>
</module>
数据库环境配置
1. MySQL安装与配置
Docker方式安装
yaml
# docker-compose.yml
version: '3.8'
services:
mysql:
image: mysql:8.0
container_name: mysql-dev
restart: always
environment:
MYSQL_ROOT_PASSWORD: root123
MYSQL_DATABASE: userdb
MYSQL_USER: appuser
MYSQL_PASSWORD: app123
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
- ./mysql/conf.d:/etc/mysql/conf.d
- ./mysql/init:/docker-entrypoint-initdb.d
command: --default-authentication-plugin=mysql_native_password
redis:
image: redis:7-alpine
container_name: redis-dev
restart: always
ports:
- "6379:6379"
volumes:
- redis_data:/data
volumes:
mysql_data:
redis_data:
MySQL配置文件
ini
# mysql/conf.d/mysql.cnf
[mysqld]
# 基本配置
default-storage-engine=INNODB
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci
# 连接配置
max_connections=1000
max_connect_errors=1000
wait_timeout=28800
interactive_timeout=28800
# 缓存配置
innodb_buffer_pool_size=1G
innodb_log_file_size=256M
innodb_log_buffer_size=16M
innodb_flush_log_at_trx_commit=1
# 查询缓存
query_cache_type=1
query_cache_size=64M
query_cache_limit=2M
# 慢查询日志
slow_query_log=1
slow_query_log_file=/var/log/mysql/slow.log
long_query_time=2
# 二进制日志
log-bin=mysql-bin
binlog_format=ROW
expire_logs_days=7
2. Redis安装与配置
Redis配置文件
conf
# redis.conf
# 基本配置
bind 0.0.0.0
port 6379
timeout 0
tcp-keepalive 300
# 内存配置
maxmemory 512mb
maxmemory-policy allkeys-lru
# 持久化配置
save 900 1
save 300 10
save 60 10000
# 日志配置
loglevel notice
logfile /var/log/redis/redis.log
# 安全配置
requirepass redis123
开发工具链配置
1. Git配置
Git全局配置
bash
# 基本配置
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
git config --global init.defaultBranch main
# 编辑器配置
git config --global core.editor "cursor --wait"
git config --global core.autocrlf input
git config --global core.safecrlf true
# 别名配置
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!cursor'
# 颜色配置
git config --global color.ui auto
git config --global color.branch auto
git config --global color.diff auto
git config --global color.status auto
# 推送配置
git config --global push.default simple
git config --global push.autoSetupRemote true
Git钩子配置
bash
#!/bin/sh
# .git/hooks/pre-commit
# 运行代码检查
echo "Running code quality checks..."
# 运行Checkstyle
mvn checkstyle:check
if [ $? -ne 0 ]; then
echo "Checkstyle check failed!"
exit 1
fi
# 运行SpotBugs
mvn spotbugs:check
if [ $? -ne 0 ]; then
echo "SpotBugs check failed!"
exit 1
fi
# 运行测试
mvn test
if [ $? -ne 0 ]; then
echo "Tests failed!"
exit 1
fi
echo "All checks passed!"
2. Docker配置
Dockerfile模板
dockerfile
# Dockerfile
FROM openjdk:17-jdk-slim
# 设置工作目录
WORKDIR /app
# 复制Maven包装器
COPY .mvn/ .mvn
COPY mvnw pom.xml ./
# 下载依赖
RUN ./mvnw dependency:go-offline -B
# 复制源代码
COPY src ./src
# 构建应用
RUN ./mvnw clean package -DskipTests
# 运行应用
EXPOSE 8080
CMD ["java", "-jar", "target/*.jar"]
Docker Compose开发环境
yaml
# docker-compose.dev.yml
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=dev
- NACOS_SERVER=nacos:8848
- MYSQL_HOST=mysql
- REDIS_HOST=redis
depends_on:
- mysql
- redis
- nacos
volumes:
- ./logs:/app/logs
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: root123
MYSQL_DATABASE: userdb
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redis_data:/data
nacos:
image: nacos/nacos-server:v2.3.0
environment:
MODE: standalone
SPRING_DATASOURCE_PLATFORM: mysql
MYSQL_SERVICE_HOST: mysql
MYSQL_SERVICE_DB_NAME: nacos
MYSQL_SERVICE_USER: root
MYSQL_SERVICE_PASSWORD: root123
ports:
- "8848:8848"
depends_on:
- mysql
volumes:
mysql_data:
redis_data:
环境验证与测试
1. 环境验证脚本
bash
#!/bin/bash
# verify-environment.sh
echo "=== Java开发环境验证 ==="
# 检查Java版本
echo "1. 检查Java版本..."
java -version
if [ $? -eq 0 ]; then
echo "✅ Java安装成功"
else
echo "❌ Java安装失败"
exit 1
fi
# 检查Maven版本
echo "2. 检查Maven版本..."
mvn -version
if [ $? -eq 0 ]; then
echo "✅ Maven安装成功"
else
echo "❌ Maven安装失败"
exit 1
fi
# 检查Git版本
echo "3. 检查Git版本..."
git --version
if [ $? -eq 0 ]; then
echo "✅ Git安装成功"
else
echo "❌ Git安装失败"
exit 1
fi
# 检查Docker版本
echo "4. 检查Docker版本..."
docker --version
if [ $? -eq 0 ]; then
echo "✅ Docker安装成功"
else
echo "❌ Docker安装失败"
exit 1
fi
# 检查数据库连接
echo "5. 检查数据库连接..."
mysql -h localhost -u root -p -e "SELECT 1" 2>/dev/null
if [ $? -eq 0 ]; then
echo "✅ MySQL连接成功"
else
echo "❌ MySQL连接失败"
fi
# 检查Redis连接
echo "6. 检查Redis连接..."
redis-cli ping 2>/dev/null
if [ $? -eq 0 ]; then
echo "✅ Redis连接成功"
else
echo "❌ Redis连接失败"
fi
echo "=== 环境验证完成 ==="
2. 项目初始化测试
bash
#!/bin/bash
# init-project.sh
echo "=== 项目初始化测试 ==="
# 创建测试项目
echo "1. 创建测试项目..."
mvn archetype:generate \
-DgroupId=com.example.test \
-DartifactId=test-project \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DinteractiveMode=false
if [ $? -eq 0 ]; then
echo "✅ 项目创建成功"
else
echo "❌ 项目创建失败"
exit 1
fi
# 进入项目目录
cd test-project
# 编译项目
echo "2. 编译项目..."
mvn clean compile
if [ $? -eq 0 ]; then
echo "✅ 项目编译成功"
else
echo "❌ 项目编译失败"
exit 1
fi
# 运行测试
echo "3. 运行测试..."
mvn test
if [ $? -eq 0 ]; then
echo "✅ 测试运行成功"
else
echo "❌ 测试运行失败"
exit 1
fi
# 打包项目
echo "4. 打包项目..."
mvn package
if [ $? -eq 0 ]; then
echo "✅ 项目打包成功"
else
echo "❌ 项目打包失败"
exit 1
fi
# 清理测试项目
cd ..
rm -rf test-project
echo "=== 项目初始化测试完成 ==="
性能优化建议
1. JVM性能调优
开发环境调优
bash
# 开发环境JVM参数
export JAVA_OPTS_DEV="-Xms512m -Xmx2g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:+UseStringDeduplication -XX:+OptimizeStringConcat -Dfile.encoding=UTF-8 -Duser.timezone=Asia/Shanghai -Dspring.profiles.active=dev"
# 启用调试信息
export JAVA_OPTS_DEV="$JAVA_OPTS_DEV -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005"
生产环境调优
bash
# 生产环境JVM参数
export JAVA_OPTS_PROD="-Xms2g -Xmx8g -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -XX:+UseStringDeduplication -XX:+OptimizeStringConcat -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/logs/heapdump.hprof -Dfile.encoding=UTF-8 -Duser.timezone=Asia/Shanghai -Dspring.profiles.active=prod"
# 启用JMX监控
export JAVA_OPTS_PROD="$JAVA_OPTS_PROD -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9999 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"
2. Maven性能优化
Maven配置优化
xml
<!-- settings.xml 性能优化配置 -->
<settings>
<!-- 并行构建 -->
<profiles>
<profile>
<id>performance</id>
<properties>
<maven.compiler.fork>true</maven.compiler.fork>
<maven.compiler.maxmem>1024m</maven.compiler.maxmem>
<maven.test.skip>false</maven.test.skip>
<maven.javadoc.skip>true</maven.javadoc.skip>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>performance</activeProfile>
</activeProfiles>
</settings>
构建优化脚本
bash
#!/bin/bash
# build-optimized.sh
echo "=== 优化构建开始 ==="
# 清理并跳过测试构建
echo "1. 快速构建(跳过测试)..."
mvn clean package -DskipTests -T 4C
# 运行测试
echo "2. 运行测试..."
mvn test -T 4C
# 生成报告
echo "3. 生成报告..."
mvn site -T 4C
echo "=== 优化构建完成 ==="
常见问题与解决方案
1. 环境配置问题
问题1:Java版本不匹配
bash
# 症状:编译时出现版本错误
# 错误信息:Source option 17 is no longer supported. Use 21 or later.
# 解决方案:
# 1. 检查JAVA_HOME环境变量
echo $JAVA_HOME
# 2. 更新Maven编译器配置
# 在pom.xml中设置正确的Java版本
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
问题2:Maven依赖下载失败
bash
# 症状:依赖下载超时或失败
# 错误信息:Could not transfer artifact
# 解决方案:
# 1. 配置阿里云镜像
# 在settings.xml中添加镜像配置
<mirrors>
<mirror>
<id>aliyun</id>
<name>Aliyun Maven</name>
<url>https://maven.aliyun.com/repository/public</url>
<mirrorOf>central</mirrorOf>
</mirror>
</mirrors>
# 2. 清理本地仓库
mvn dependency:purge-local-repository
2. 开发工具问题
问题3:Cursor IDE插件冲突
json
// 解决方案:禁用冲突插件
{
"extensions.ignoreRecommendations": false,
"extensions.autoUpdate": false,
"java.configuration.runtimes": [
{
"name": "JavaSE-17",
"path": "/usr/lib/jvm/java-17-openjdk"
}
]
}
问题4:数据库连接问题
yaml
# 解决方案:检查数据库配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/userdb?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
总结
通过本章的学习,我们完成了Java开发环境的全面配置,包括:
核心配置
- JDK环境:多版本管理、JVM参数优化
- 构建工具:Maven/Gradle配置、插件管理
- IDE集成:Cursor IDE插件、代码质量工具
- 数据库环境:MySQL、Redis配置
- 开发工具链:Git、Docker配置
最佳实践
- 版本管理:使用SDKMAN等工具管理多版本
- 性能优化:合理的JVM参数和构建配置
- 代码质量:集成Checkstyle、SpotBugs等工具
- 环境隔离:使用Docker进行环境隔离
- 自动化:脚本化环境验证和项目初始化
关键优势
- 标准化:统一的开发环境配置
- 高效性:优化的构建和运行性能
- 可维护性:清晰的配置管理和文档
- 可扩展性:支持团队协作和CI/CD集成
在下一节中,我们将学习MCP服务器的安装与配置,为MCP在Java项目中的应用做好准备。通过系统性的环境配置,我们能够充分发挥MCP和Cursor IDE的强大功能,实现高效的Java开发。
下一节预告:我们将详细介绍MCP服务器的安装与配置,包括服务器选择、配置管理、连接建立等,为MCP在Java项目中的应用奠定坚实基础。