如何通过CMD启动Spring项目?编译代码时遇报错求助
javac Hey there! Let's break down why you're running into issues compiling your EasyTripApplication.java directly with the javac command—and how to fix it properly.
The Root Problem
Spring Boot projects rely on dozens of external dependencies (like Spring Core libraries, Boot starters, etc.). When you run javac EasyTripApplication.java directly, the compiler has no idea where to find all those required jar files. It only looks at the current directory, so it throws errors because it can't resolve imports like org.springframework.boot.SpringApplication.
The Proper Solutions (Highly Recommended)
Spring Boot is built to work with build tools like Maven or Gradle, which handle dependency management, compilation, and packaging automatically. Here's how to use them:
1. If Your Project Uses Maven
- First, confirm your project root has a
pom.xmlfile (this is Maven's config file that defines all your dependencies). - Open CMD, navigate to your project's root directory (where
pom.xmllives), and run:- To compile the project:
mvn clean compile - To start the app directly:
mvn spring-boot:run - Or, package it into an executable jar and run it:
mvn clean package(this creates a jar in thetargetfolder)java -jar target/easytrip-<version>.jar(replace<version>with your project's version frompom.xml)
- To compile the project:
2. If Your Project Uses Gradle
- Check for a
build.gradle(orbuild.gradle.ktsfor Kotlin) file in your project root. - Open CMD, go to the project root, and run:
- To compile:
gradlew.bat build(Windows) or./gradlew build(Linux/Mac) - To start the app:
gradlew.bat bootRun(Windows) or./gradlew bootRun(Linux/Mac) - To run the packaged jar:
- Build first with the command above
java -jar build/libs/easytrip-<version>.jar
- To compile:
Manual Compilation (Not Recommended)
If you really need to use javac directly (it's tedious!), you'll need to:
- Download all your project's dependency jars (grab them from Maven Central or copy them from your build tool's cache) and put them in a folder like
libin your project root. - Compile with the classpath pointing to all those jars:
(Note: Usejavac -cp "lib/*;." com/easytrip/EasyTripApplication.java:instead of;if you're on Linux/Mac.) - To run the compiled class, you'll also need to specify the classpath:
java -cp "lib/*;." com/easytrip/EasyTripApplication
Again, this is not practical for Spring Boot projects—stick with Maven/Gradle to save yourself a headache.
内容的提问来源于stack exchange,提问作者Roman Shmandrovskyi

