Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain real Class object for Spring bean

People also ask

Can @bean be used at class level?

With @Bean you aren't placing this annotation at the class level. If you tried to do that you would get an invalid type error. The @Bean documentation defines it as: Indicates that a method produces a bean to be managed by the Spring container.

How do you get the BeanFactory reference in any class?

I can have my class implement BeanFactoryAware to get a reference to my beanfactory. Then I can do beanFactory. getBean("name"); to get access to a single bean.

Is @bean a class level annotation?

@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> , such as: init-method , destroy-method , autowiring , lazy-init , dependency-check , depends-on and scope .


Spring's interface-based proxies implement TargetClassAware.


Or you can just call: AopUtils.getTargetClass(java.lang.Object) It is a static method call.


You can cast the proxied object to get the object and class it acts as a proxy for (see TargetSource):

Advised advised = (Advised) proxy;
Class<?> cls = advised.getTargetSource().getTargetClass();

Generally you should follow the Spring principles and keep obtaining the correct class as unobtrusive as possible. Meaning that as little classes as possible should depend on the Spring Framework APIs (maybe add a ClassLocator and a SpringProxyClassLocator implementation).


AopUtils.getTargetClass only unwraps one level. Use AopProxyUtils.ultimateTargetClass(instance) instead.

(I'm aware this is an 11 years old question, but it's still coming up high in Google, so it benefits from a new answer)