Skip to content

Instantly share code, notes, and snippets.

@mvitz
Created May 28, 2018 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvitz/27f10e6679d92894347a01517583c876 to your computer and use it in GitHub Desktop.
Save mvitz/27f10e6679d92894347a01517583c876 to your computer and use it in GitHub Desktop.
Simplified example of how Spring Boot enhances @configuration classes with CGLib to intercept internal calls to other public methods
public class Config {
public static void main(String[] args) {
Map<String, Object> beans = new HashMap<>();
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(Config.class);
enhancer.setCallback((MethodInterceptor) (obj, method, arguments, proxy) -> {
String name = method.getName();
if (!beans.containsKey(name)) {
Object bean = proxy.invokeSuper(obj, arguments);
beans.put(name, bean);
}
return beans.get(name);
});
Config config = (Config) enhancer.create();
System.out.println(config.getClass());
config.foo().doSomething();
config.foo().doSomething();
}
public Bar bar() {
System.out.println("Config.bar");
return new Bar();
}
public Foo foo() {
System.out.println("Config.foo");
return new Foo(bar());
}
public static class Foo {
private final Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
public void doSomething() {
System.out.println(this.toString() + "#" + bar.toString());
}
}
public static class Bar {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment