在 IntelliJ IDEA 中使用 Gradle 的最佳实践

目标

在 IDEA 中建立一个带有 Spring 框架等依赖的 Java 工程,并用 Gradle 作为包管理器,该项目在 Tomcat 中运行

How

Step 1: 使用 Gradle 或者 IDEA 自带的向导,建立 Gradle 工程

Step 2: 向 build.gradle 中添加插件、依赖等等,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
group 'me.ericfu'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'war'

sourceCompatibility = 1.8

repositories {
mavenCentral()
}

dependencies {
compile group: 'org.springframework', name: 'spring-core', version: '4.3.2.RELEASE'
compile group: 'org.springframework', name: 'spring-context', version: '4.3.2.RELEASE'
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.2.RELEASE'
compile group: 'org.springframework', name: 'spring-jdbc', version: '4.3.2.RELEASE'

providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'

testCompile group: 'junit', name: 'junit', version: '4.11'
}

Tips: Dependency 项可以从 mvnrepository.com 上直接 copy 过来,不用手打了

Step 3: 在 IDEA 的 Gradle project 面板中,点第一个 Refresh 按钮,IDEA 会自动运行 gradle build,并导入新的依赖。以后如果修改了 build.gradle,重复此操作。

Step 4: 想要在 Tomcat 中运行,在 IDEA 中新建一个 Run configuration,设置好 Tomcat 的目录,并添加一个 artifact 用于执行。IDEA 已经自动生成了两个 artifact,一个是打包成 war 的,另一个带有 exploded,意思是不打包的。任选一个即可。