01: /*
02: * Copyright 2002-2007 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.springframework.instrument.classloading;
18:
19: import java.lang.instrument.ClassFileTransformer;
20: import java.lang.instrument.Instrumentation;
21:
22: import org.springframework.instrument.InstrumentationSavingAgent;
23: import org.springframework.util.Assert;
24: import org.springframework.util.ClassUtils;
25:
26: /**
27: * Load time weaver relying on {@link Instrumentation}.
28: *
29: * <p>Start the JVM specifying the java agent to be used, like so:
30: *
31: * <p><code class="code">-javaagent:path/to/spring-agent.jar</code>
32: *
33: * <p>where <code>spring-agent.jar</code> is a JAR file containing the
34: * {@link InstrumentationSavingAgent} class.
35: *
36: * <p>In Eclipse, for example, set the Run configuration's JVM args to be of
37: * the form:
38: *
39: * <p><code class="code">-javaagent:${project_loc}/lib/spring-agent.jar</code>
40: *
41: * @author Rod Johnson
42: * @since 2.0
43: * @see InstrumentationSavingAgent
44: */
45: public class InstrumentationLoadTimeWeaver implements LoadTimeWeaver {
46:
47: public void addTransformer(ClassFileTransformer transformer) {
48: Assert.notNull(transformer, "Transformer must not be null");
49: Instrumentation instrumentation = InstrumentationSavingAgent
50: .getInstrumentation();
51: if (instrumentation == null) {
52: throw new IllegalStateException(
53: "Must start with Java agent to use InstrumentationLoadTimeWeaver. See Spring documentation.");
54: }
55: instrumentation.addTransformer(transformer);
56: }
57:
58: /**
59: * We have the ability to weave the current class loader when starting the
60: * JVM in this way, so the instrumentable class loader will always be the
61: * current loader.
62: */
63: public ClassLoader getInstrumentableClassLoader() {
64: return ClassUtils.getDefaultClassLoader();
65: }
66:
67: /**
68: * This implementation always returns a {@link SimpleThrowawayClassLoader}.
69: */
70: public ClassLoader getThrowawayClassLoader() {
71: return new SimpleThrowawayClassLoader(
72: getInstrumentableClassLoader());
73: }
74:
75: }
|