Skip to content

Autowiring by name (interface vs class) [SPR-16174] #20722

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
spring-projects-issues opened this issue Nov 8, 2017 · 1 comment
Closed

Autowiring by name (interface vs class) [SPR-16174] #20722

spring-projects-issues opened this issue Nov 8, 2017 · 1 comment
Assignees
Labels
in: core Issues in core modules (aop, beans, core, context, expression)

Comments

@spring-projects-issues
Copy link
Collaborator

spring-projects-issues commented Nov 8, 2017

Max Samsonov opened SPR-16174 and commented

Lets say we have 2 beans that implement interface A:

interface A {}
class B implements A {}

@Configuration
public class C {
  @Bean public A red() { return new B(); }
  @Bean public A black() { return new B(); }
}

If we autowire them later, in 2 fields, we won't get an exception.
But, we will randomly get same bean injected in both fields.

@Service
public class ServiceImpl {
  private final A red;
  private final A black;
  public ServiceImpl(A red, A black) {
    this.red = red;
    this.black = black;
  }
}

Otherwise, if we change type of fields (from interface to class), it will work as expected.

@Service
public class ServiceImpl {
  private final B red;
  private final B black;
  public ServiceImpl(B red, B black) {
    this.red = red;
    this.black = black;
  }
}

Affects: 4.3.12

Issue Links:

@spring-projects-issues
Copy link
Collaborator Author

Juergen Hoeller commented

I can't reproduce this: Such an arrangement injects fine for me, selecting the target beans by type first and then matching each bean by name against the parameter name in a second pass. Could you please double-check your effect and provide a corresponding unit test that reliably fails for you in the interface case but works in the target class case?

FWIW, we generally recommend to be as specific as possible in your @Bean return type signature, i.e. declaring B as a return type in your scenario. This allows the container to introspect the implementation type early, not just learning about it once the bean is actually created.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
in: core Issues in core modules (aop, beans, core, context, expression)
Projects
None yet
Development

No branches or pull requests

2 participants