Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Autowire beans by interface but exclude specific bean at injection time

I'm currently injecting a list of Spring @Component which all implement the same interface. This works fine however I want to inject this same list into an instance of a bean in that list so I can act on all the other beans in that list. I can't see how to exclude a specific bean from that injection, I can filter the list after injecting it but this of course results in a Spring circular dependency exception at startup. My question is can I at the point of injecting tell spring to exclude the class being injected to from the list of beans?

public interface Foo {
    String doSomething();
}
@Component
public class Foo1 implements Foo {

    private final List<Foo> foos;

    public Sample(final List<Foo> foos) {
        //Don't include Foo1
        this.foos = foos;
    }

    public String doSomething() {
        foos.forEach(foo -> foo.doSomething());
        return "aString";
    }
}

@Component
public class Foo2 implements Foo {

    private final List<Foo> foos;

    public Sample(final List<Foo> foos) {
        //Don't include Foo2
        this.foos = foos;
    }

    public String doSomething() {
        foos.forEach(foo -> foo.doSomething());
        return "anotherString";
    }
}
@Component
public class Foo3 implements Foo {
//and so on
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Instead of injecting a list in the constructor, you can look up all beans of type Foo in the doSomething methods, and then exclude the current one. To look up, use any of the methods from BeanFactoryUtils, like beanNamesForTypeIncludingAncestors, and then exclude foo1, which is the bean name for class Foo1. The look up can even be coded into a default method in interface Foo.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!