Affects: Spring 5.3.18

When registering a new bean X2 of type X and marking it as the primary implementation, a previously @Autowired field is still returning the previous instance type X1 when the parent bean instance is constructed.

Expected: The new primary class X2 is injected. The class with the @Autowired field is marked with @Scope("prototype"). Actual: The previous class X1 is injected instead.

This code screenshot should be able to explain the issue better: Spring Unexpected @Autowired bean when newly registered bean is set as Primary

PS. If the parent bean has not been retrieved prior to the bean definition, it works fine. The correct bean X2 is being returned.

https://github.com/rj-cam/autowire-primary/tree/main/src/test/java/com/example/autowireprimary


Comment From: snicoll

When registering a new bean X2 of type X and marking it as the primary implementation, a previously @Autowired field is still returning the previous instance type X1 when the parent bean instance is constructed.

The key here is that you're doing that once the context has refreshed, which is something you can't do. The BeanDefinitionRegistry.class.cast(ctx) should give you a hint you're trying to access something you're not supposed to.