javaspringautowiredprototype-scope

Is there a way to get all beans with scope prototype that are injected via @Autowired?


Injecting bean with scope prototype with @Autowired usually doesn't work as expected. But when writing code, it's easy to accidentally inject a prototype.

Is there a way to get a list of all @Autowired fields and methods and to match that with a Spring AppContext to check for this?


Solution

  • One approach could be to override org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor(which is responsible for processing @Autowired, @Inject, @Resource etc) and perform the checks that you have mentioned in this overridden bean post processor. However, AutowiredAnnotationBeanPostProcessor gets registered with quite a few of the common custom namespaces (context:component-scan, context:annotation-config etc), so these custom annotations will have to be replaced with the corresponding bean variation and the overridden post processor also registered as a bean.