Use the spring-loaded open-source project to implement hot deployment of java programs and web applications
JDK1.5 and later provide java. lang. instrument. Instrumentation, that is, the java agent mechanism can implement redefinition and retransform of classes. Redefinition corresponds to Instrumentation. redefineClasses (), which can implement hot replacement of classes, but unfortunately has limited functions.
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 belifted in future versions.
I recently met spring-loaded, an open-source project. I read the official introduction documents and found that it is much more powerful than the built-in 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.
After your own attempts, we found that using the spring-loaded project can indeed implement hot deployment of java applications. The following describes how to introduce spring-loaded into a project. Run the following code and modify the. say () method to check whether the JVM can be dynamically changed without restarting.
package test;import demo.A;public class TestPreMain{// -javaagent:springloaded-1.2.0.RELEASE.jar -noverifypublic static void main(String[] args) throws Exception{A a = new A();while (true){a.say();Thread.sleep(3000);}}}
To use spring-loaded for hot deployment, you only need to add the following startup parameters when starting JVM.
-javaagent:springloaded-1.2.0.RELEASE.jar -noverify
If it is started through eclipse, you can set it in run confiuration.
Next, let's take a look at how to use spring-loaded in tomcat to implement hot deployment of war packages. Place the downloaded springloaded-1.2.0.RELEASE.jar in the % TOMCAT_HOME %/bin/directory, and modify catalina. bat under that directory
set JAVA_OPTS=-javaagent:springloaded-1.2.0.RELEASE.jar -noverify
In this way, the installation of spring-loaded is completed, and the webapp deployed under tomcat can be detected. The hot deployment of the application is realized without restarting tomcat.