Created
May 28, 2018 15:13
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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