'How do I avoid name conflict when defining @Bean in an abstract class?

I want to have something like this:

public class AbstractHandler {
    @Bean
    protected abstract RouterFunction<ServerResponse> route();
}
public class SomeHandler extends AbstractHandler {
    @Override
    protected RouterFunction<ServerResponse> route() {
        // defining some route
    }
}
public class AnotherHandler extends AbstractHandler {
    @Override
    protected RouterFunction<ServerResponse> route() {
        // defining another route
    }
}

I want every subclass to have its own bean. However, the code above results in a name conflict, as both beans would have the same name (because the bean takes name from a method).

It is possible to annotate the method with @Bean("uniqueNameHere") in each sub-class but it is a little annoying, sometimes I forget to add this annotation and it results in a bug.

I thought about something like specifying an additional abstract method in the abstract class and using this method for getting a bean name somehow. However, I did not find a way to do so.

So is there any way to make every implementation of an abstract class have a bean of its own without adding a @Bean annotation in each of them?

Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source