JDK1.5之后提供了java.lang.instrument.Instrumentation,即java agent機制可以實現類的redefinition和retransform。
redefinition相應Instrumentation.redefineClasses()可以實現類的熱替換。但遺憾的是功能非常有限。
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 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項目。確實能夠實現java應用的熱部署。以下介紹下怎樣將spring-loaded引入到項目中。
我們能夠執行以下的這段代碼,然后改動A.say()方法,看看在不重新啟動JVM的情況下,能否夠動態改變。
package test; import demo.A; public class TestPreMain { // -javaagent:springloaded-1.2.0.RELEASE.jar -noverify public static void main(String[] args) throws Exception { A a = new A(); while (true) { a.say(); Thread.sleep(3000); } } }
為了使用spring-loaded實現熱部署。我們僅僅須要在啟動JVM的時候。添加例如以下的啟動參數就可以
-javaagent:springloaded-1.2.0.RELEASE.jar -noverify

接下來我們看下怎樣在tomcat中使用spring-loaded實現war包的熱部署。將下載的springloaded-1.2.0.RELEASE.jar放到%TOMCAT_HOME%/bin/文件夾下,然后改動該文件夾下的catalina.bat
set JAVA_OPTS=-javaagent:springloaded-1.2.0.RELEASE.jar -noverify
這樣就完畢了spring-loaded的安裝,可以檢測tomcat下部署的webapp,在不重新啟動tomcat的情況下。實現應用的熱部署。