Spring Loaded is a JVM agent for reloading class file changes

Posted 沧海一滴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Loaded is a JVM agent for reloading class file changes相关的知识,希望对你有一定的参考价值。

 

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.2.5.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>

 

JDK1.5之后提供了java.lang.instrument.Instrumentation,即java agent机制能够实现类的redefinition和retransform。

 

redefinition对应Instrumentation.redefineClasses()能够实现类的热替换,但遗憾的是功能很有限。

1
2
3
4
The redefinition may change method bodies, the constant pool and attributes.
The redefinition must not add, remove or rename fields or methods, change the
signatures of methods, or change inheritance.  These restrictions maybe be
lifted in future versions.


最近遇到一个开源项目spring-loaded,看了下官方的介绍文档:发现它功能比JDK自带的强大多了。

Spring Loaded is a JVM agent for reloading class file changes whilst a JVM is running. It transforms classes at loadtime to make them amenable to later reloading. Unlike \'hot code replace\' which only allows simple changes once a JVM is running (e.g. changes to method bodies), Spring Loaded allows you to add/modify/delete methods/fields/constructors. The annotations on types/methods/fields/constructors can also be modified and it is possible to add/remove/change values in enum types.

Spring Loaded is usable on any bytecode that may run on a JVM, and is actually the reloading system used in Grails 2.

https://github.com/spring-projects/spring-loaded

经过自己的尝试,发现使用spring-loaded项目,确实可以实现java应用的热部署。下面介绍下如何将spring-loaded引入到项目中。我们可以运行下面的这段代码,然后修改A.say()方法,看看在不重启JVM的情况下,是否能够动态改变。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package test;
 
import demo.A;
 
public class TestPreMain
{
 
    // -javaagent:springloaded-1.2.0.RELEASE.jar -noverify

(c)2006-2024 SYSTEM All Rights Reserved IT常识