A Day in the Life of an Engineer: A Weird Spring Stuff
Coming back from vacation and one of the things I encountered is a "bug" that was raised by a co-worker wherein an Autowired bean fields become NULL over its lifetime.
At first, I thought it was a variation of my all-time favorite weird Spring stuff which is Circular Dependency, but alas it wasn't. It basically took me on-and-off the whole afternoon trying to decipher what the root issue; I pretty much rewrote the auto wiring of the beans and it was still happening...to which point I started questioning (again) why I ended up as a software developer.
Staring at the IntelliJ breakpoint where the issue occurs, I noticed that the method has a final modifier--a Java feature that I rarely really use on a class let alone on a method.
领英推荐
@AsyncCacheable(cacheSpec = "service")
public final Mono<ProfileSegmentResponse> getProfileResponse(long teamId) {
// delegationService becomes null here
log.info("delegationService is {}", delegationService);
return getTeamApiKey(teamId)
.flatMap(apiKey -> delegationService
.getTeamProfileSegment(
new ProfileSegmentRequest(apiKey, null, null, null))
.doOnSuccess(response -> log.info("segment size: {}",
response.getProfileSegments().size())));
}
I just thought...well, guessed (out of desperation) that Spring has some weird thing with final methods because of the inversion of control thing...and sure enough, after removing that qualifier from the method (which was never really needed), the issue was gone!
I couldn't just leave it there as I didn't understand what was happening, but my initial Google-fu skills came up empty...asking ChatGPT did confirm that there are some weird unexpected behavior with final methods in Spring auto-injection but my prompts never gave me a satisfactory answer. I tried again with Google which brought me to this StackOverflow question which mirrors exactly what I encountered.
It basically boils down to how CGLIB proxying works which was how the bean was created in our case. I should probably try to understand this more. Someday, maybe.