Skip to content

Instantly share code, notes, and snippets.

@moelholm
Created September 20, 2017 20:37
Show Gist options
  • Save moelholm/c14663d494c8c123110285a20553b252 to your computer and use it in GitHub Desktop.
Save moelholm/c14663d494c8c123110285a20553b252 to your computer and use it in GitHub Desktop.
Unwrapping a Spring Bean from its proxy (if any)
/**
* Gets a bean from the Spring context - stripping the proxy (if any).
*
* @param clazz type of the bean to find
* @return the bean (not a proxy)
*/
protected <T> T getBeanWithoutProxy(Class<T> clazz) {
T bean = applicationContext.getBean(clazz);
if (AopUtils.isAopProxy(bean) && bean instanceof Advised) {
try {
return (T) ((Advised) bean).getTargetSource().getTarget();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return bean;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment