1

I have the name of a bean of unknown scope. I'm trying to determine its static type (the class annotated with @Component, or the return type of the @Bean factory method) in a reliable way (that deals with proxies etc).

  • BeanFactory.getType(beanName) gives me a proxy class.
  • BeanFactory.getBeanDefinition(beanName).getResolvableType() in many cases gives me an EmptyType.

All utility methods for determining the bean type, like AopUtils.getTargetClass() and AopProxyUtils.ultimateTargetClass() require an actual instance, which I can not safely obtain for non-singletons.

If the bean is created by a factory method, I can find the method via beanDefinition.getSource() and get its return type from there. But nothing seems possible for @Component annotated classes. I can get the class name, but not the class itself (and loading it by name is a can of worms I'd rather avoid).

Is there anything I can do here?

kaqqao
  • 12,984
  • 10
  • 64
  • 118
  • Of course not. Names are arbitrary. But how can you have a bean of unknown scope and type? Don't you hjave the source code? If not, why not? And even so, you have the .class file, you can run `javap` on it. – user207421 May 20 '21 at 00:55
  • I might be missing the obvious here, but `ConfigurableApplicationContext context; Class> cls = context.getBean("yourName").getClass();`? – Eugene May 21 '21 at 02:52
  • @Eugene Unfortunately, `context.getBean("yourName")` is only safe for singletons. For prototype scope it would trigger bean creation (which can have side effects), and for request, session, etc scopes it would blow up if called outside of a web request. But, even it were safe, it would still be insufficient, as you still must deal with proxies. `getClass` would give you `Proxy` in many cases... That's what `AopProxyUtils` help with. – kaqqao May 21 '21 at 15:47
  • hw about using `BeanFactoryPostProcessor` and `beanFactory.getBeanDefinition(beanName)`? `BeanFactoryPostProcessor` is called when all beans are loaded, but none are instantiated. The only problem is that if you have something like this: `static class MyService implements IMyService {} @Bean @Scope("prototype") public IMyService service() { return new MyService(); }`, `beanFactory.getBeanDefinition(beanName).getResolvableType()` will return `IMyService` instead of `MyService` – Eugene May 22 '21 at 04:05

0 Answers0