Question

I understand Spring avoids using the -javaagent vm option in order to get its AspectJ load time weaving to work and relies instead on a classloader to start the agent.

I thought that the Java specification dictated that the only way to use a Java agent was through the -javaagent vm option.

Am I wrong? Can someone please direct me to the official Java specification/documentation that would clarify my interrogation?

Was it helpful?

Solution

I found some information about loading java agents in this interesting blog post.

Instrumentation Agent To enable JVM instrumentation, you have to provide an agent (or more) that is deployed as a JAR file. An attribute in the JAR file manifest specifies the agent class which will be loaded to start the agent.

There is 2 ways to load the agent:

  • with a command-line interface: by adding this option to the command-line: -javaagent:jarpath[=options] where jarpath is the path to the agent JAR file. options is the agent options. This switch may be used multiple times on the same command-line, thus creating multiple agents. More than one agent may use the same jarpath.
  • by dynamic loading: the JVM must implement a mechanism to start agents sometime after the the VM has started. That way, a tool can "attach" an agent to a running JVM (for instance profilers or ByteMan)

After the JVM has initialized, the agent class will be loaded by the system class loader. If the class loader fails to load the agent, the JVM will abort. ...

Yes official documentation/specification would be more than welcome...

Edit 1: At last I came across some relevant and official documentation: API Javadoc for dynamically loading an agent as described in second bullet point above: see here for VirtualMachine class and here for loadAgent method.

Edit 2: Also see this other blog post. It explains clearly the difference between static loading of a javaagent at startup and dynamic loading of a javaagent at runtime.

OTHER TIPS

Here a library that initializes aspectj and spring-aspects at runtime by injecting instrumentation: https://github.com/subes/invesdwin-instrument

So no more need for explicit -javaagent argument.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top