Use Spring Connect to implement beans that mark interfaces (interfaces) out of the list
I have a set of classes that extend abstract classes called Executor. Let’s say these classes are ExecutorOne,
ExecutorTwo, and
ExecutorThree
.
ExecutorFour
, but also implements the interface NotUsable
I’m using Spring 4.x to inject instances of all of the above beans into the list.
@Autowired
private final List<Executor> executors;
Is there any mechanism for me not to inject a bean of type ExecutorFour
? In the list executors
? I want the list executors
to contain only three beans, which belong to the ExecutorOne type, ExecutorTwo, and ExecutorThree
I’m trying to see @Conditional
comment, but it doesn’t seem useful in this case.
Thanks in advance.
Solution
There is another option that helps achieve what you are trying to achieve but does not answer the question directly.
Spring does not have such an exclusion mechanism, after all, all 4 beans are valid spring beans, and all are created.
However, instead of the NotUsable
tagged interface, you can use the Usable
interface. Here’s an (almost self-explanatory) example:
interface Executor {}
interface UsableExecutor extends Executor {}
class Executor1 implements UsableExecutor{...}
class Executor2 implements UsableExecutor{...}
class Executor3 implements UsableExecutor{...}
class Executor4 implements Executor {} // note, doesn't implement UsableExecutor
@Component
class SomeClassWithUsableExecutors {
private final List<UsableExecutor> usableExecutors;
an autowired constructor - only 3 elements will be in the list
public SomeClassWithUsableExecutors(List<UsableExecutor> usableExecutors) {
this.usableExecutors = usableExecutors;
}
}