1. 程式人生 > >IDEA + Spring Boot + JRebel 熱部署的幾種方式和不能自動編譯的解決方案

IDEA + Spring Boot + JRebel 熱部署的幾種方式和不能自動編譯的解決方案

方式一

Application 類右鍵選擇 Run/Debug with JRebel ‘Application’

方式二

Maven、Gradle 載入了 org.springframework.boot 外掛後,在 Maven、Gradle window 中,找到 bootRun(Module name -> Tasks -> application),右鍵選擇 Run/Debug with JRebel ‘Module name’ [bootRun]

  • Maven
<build>
    <plugins>
        <plugin>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
  • Gradle
buildscript {
	ext {
        springBootVersion = "2.0.4.RELEASE"
    }
    
	dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
    }
}

apply plugin: "org.springframework.boot"

Gradle window

自動編譯

以上兩種方式都採用 Spring Boot 內建 Tomcat 啟動,但是內建 Tomcat 不會自動 Update classes and resources,需要按 Ctrl + F9 重新編譯,如何焦點離開 IDEA 後就自動編譯呢?

  1. 啟用 Module 的 JRebel 自動編譯:開啟 IDEA 左側 Sidebar 中的 JRebel Panel(View -> Tool Windows -> JRebel),然後勾選需要的 Module。
    JRebel Panel
    Jrebel 外掛會自動在 resources 目錄底下生成一個 rebel.xml。

  2. 允許 IDEA 自動編譯:在 Maintenance(Ctrl + Shift + Alt + /) -> Registry

    中勾選 compiler.automake.allow.when.app.running,此時 IDEA 會自動選中 Settings -> Build, Execution, Deployment -> Compiler 中的 Build project automatically

如果更改了 Project Structure 導致不能用 JRebel 啟動或者啟動後不能自動編譯,在 Project Structure 不報錯的情況下,刪除 rebel.xml,重新勾選即可,如果還是沒用,在 Project Structure 不報錯的情況下,刪除 .idea、.iml、rebel.xml 重新匯入專案勾選即可。

方式三(推薦)

使用外部 Tomcat 也可以自動編譯,就像非 Spring Boot 專案一樣,而且不需要啟用 JRebel 自動編譯和允許 IDEA 自動編譯。除此之外,因為上文的方式自動編譯是靜默的,你不知道重新編譯是否完成,而外部 Tomcat 的方式,焦點離開 IDEA 後,工作列會有進度提示,但是此方式啟動較慢。

  1. 新增啟動類
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class SpringBootApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }
}
  1. 新增 war 外掛:
  • Maven
<packaging>war</packaging>
<dependency>
	……
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- 移除內建 Tomcat -->
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
	……
</dependency> 
  • Gradle
apply plugin: 'war'

新增外掛後會在 Project Structure -> Project Settings -> Artifacts 自動生成 Web Application: Archive

  1. 配置外部 Tomcat,工具欄使用 JRebel 啟動即可: