Skip to content

Change in BeanFactoryUtils.beanNamesForTypeIncludingAncestors() Behavior in Spring Framework 6.2.x causing ClassCastExceptions #34300

@rj-cam

Description

@rj-cam

There is an unexpected change in behavior in how BeanFactoryUtils.beanNamesForTypeIncludingAncestors() as well as ListableBeanFactory.getBeanNamesForType(ResolvableType) handles generic types in the new Spring Framework 6.2.x compared to 6.1 and even in 5.x.

HOW TO REPRODUCE
I was able to reproduce the issue and verify it in the older versions. Just clone the repository, change the Spring Boot version accordingly, build and run the one and only JUnit test: https://github.com/rj-cam/beans-for-type/tree/main

Please refer to the README.MD for a summary of the code.

IMPACT
Unfortunately, due to additional beans being included that are superclasses of the expected generic type, we are now facing a slew of unexpected java.lang.ClassCastException.

For example:

java.lang.ClassCastException: class com.x.security.core.biz.domain.prelogin.PreloginInitRequest cannot be cast to class com.x.commons.core.biz.domain.TwoFAuthBizRequest (com.x.security.core.biz.domain.prelogin.PreloginInitRequest and com.x.commons.core.biz.domain.TwoFAuthBizRequest are in unnamed module of loader org.apache.catalina.loader.ParallelWebappClassLoader @4663f2d1)

Please advise if this is the expected behavior in Spring Framework from now on and if there is a way to access the old functionality. Or if not, hopefully, it's a simple fix.

Sadly, this is a showstopper for our upgrade to the latest Spring Framework version. I'm thinking of a workaround to double-check the generic type and ensure it is a sub-class of the expected type (CharlieRequest in Processor<CharlieRequest>) but I am stuck trying to get the actual type. Using ResolvableType.forInstance(bean).getGeneric(0) on the errant CharlieSubGenericProcessor<REQ extends CharlieSubRequest> bean returned by BeanFactoryUtils is returning ? for its generics type.

Metadata

Metadata

Assignees

Labels

in: coreIssues in core modules (aop, beans, core, context, expression)type: regressionA bug that is also a regression

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions