Spring Boot Hot swapping

现代IDEs(Eclipse, IDEA等)都支持字节码的热交换,所以如果你做了一个没有影响类或方
法签名的改变,它会利索地重新加载并没有任何影响。
Spring Loaded在这方面走的更远,它能够重新加载方法签名改变的类定义。如果对它进行一
些自定义配置可以强制ApplicationContext刷新自己(但没有通用的机制来确保这对一个运行
中的应用总是安全的,所以它可能只是一个开发时间的技巧)。
1.假设我有一个控制类SimpleController:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.cjoop.com.cjoop.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* Created by chenjun on 2016-08-15.
*/
@Controller
public class SimpleController {

@RequestMapping("/")
@ResponseBody
public String home(){
return "Hello World!";
}
}

2.当我们启动了这个web项目后(一直保持启动状态),我想把SimpleController类的home方法改成这个样子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.cjoop.com.cjoop.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* Created by chenjun on 2016-08-15.
*/
@Controller
public class SimpleController {

@RequestMapping("/")
@ResponseBody
public String home(){
return say("cjoop");
}

public String say(String name){
return "Hello World!" + name;
}
}

如果你使用的是IDEA,执行Ctrl+Shift+F9,重新编译该文件,然后访问地址http://localhost:8080/ ,你会发现输出的结果还是Hello World!,没有重新加载,那我们就得重新启动服务器。
Spring给我们提供了一个热交换的功能,就是springloaded,maven工程添加以下配置:

1
2
3
4
5
6
7
8
9
10
11
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.6.RELEASE</version>
</dependency>
</dependencies>
</plugin>

gradle工程添加以下配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
group 'com.cjoop'
version '1.0-SNAPSHOT'

buildscript {
ext {
springBootVersion = '1.3.5.RELEASE'
}
repositories {
mavenLocal()
jcenter()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath 'org.springframework:springloaded:1.2.6.RELEASE'
}
}

apply plugin: 'maven'
apply plugin: 'idea'
apply plugin: 'spring-boot'

sourceCompatibility = 1.7
targetCompatibility = 1.7

idea {
module {
inheritOutputDirs = false
outputDir = file("$buildDir/classes/main/")
testOutputDir = file("$buildDir/classes/test/")
}
}

repositories {
mavenLocal()
jcenter()
}

dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("org.springframework.boot:spring-boot-starter-test")
}

再次运行项目,重复之前步骤1和2,结果变成了Hello World!cjoop,这就是springloaded不一样的体验。动手自己体验吧(^-^)