Get all beans implementing a generic interface in Spring

后端 未结 2 721
无人共我
无人共我 2020-12-19 09:21

How do I get a reference of all beans implementing a specific generic interface (e.g. Filter>) in Spring?

This is what I want to achieve wi

2条回答
  •  有刺的猬
    2020-12-19 09:32

    If your question is "does Spring have a nicer way to do this", then the answer is "no". Hence, your method looks like the ubiquitous way to achieve this (get all beans of the raw class, then use reflection to look up the generic bound and compare it with the target's class).

    In general, using generic information at runtime is tricky if possible at all. In this case you can get the generic bounds, but you're not really getting much benefit from the generic definition itself, other than using it as a form of annotation to check manually.

    In any case, you will have to perform some kind of check on the returned object, so your original code block isn't going to work; the only variation is in the implementation of doesFilterAcceptEventAsArgument. The classic OO way, would be to add an abstract superclass with two methods as follows (and add the latter to the Filter interface):

    protected abstract Class getEventClass();
    
    public boolean acceptsEvent(Object event) // or an appropriate class for event
    {
        return getEventClass().isAssignableFrom(event.getClass());
    }
    

    This is kind of a pain because you'll have to implement the trivial getEventClass() methods in every implementation to return the appropriate class literal, but it's a known limitation of generics. Within the bounds of the language, this is likely the cleanest approach.

    But yours is fine for what it's worth.

提交回复
热议问题