androberz
androberz

Reputation: 934

Spring autowiring parameter by name

I have two beans with the type InterfaceA. I was trying to inject the bean into an argument of a @Bean method using @Qualifier to autowire by name. I was surprising that Spring can't resolve the proper bean unless your parameter name is matching the bean name.

I was trying:

@Component
public class ClassA implements InterfaceA {
}

@Component
public class ClassB implements InterfaceA {
}

@Configuration
public class AppConfig {
    @Bean
    @Autowired
    @Qualifier("classA")
    public SomeOtherClass someOtherClass(InterfaceA object) {...}
}

But got the NoUniqueBeanDefinitionException. However if I use parameter name matching the component name it works fine.

@Configuration
public class AppConfig {
    @Bean
    @Autowired
    public SomeOtherClass someOtherClass(InterfaceA classA) {...}
}

Could someone explain why I can't use autowiring by name with @Resource or @Qualifier here?

Upvotes: 3

Views: 4883

Answers (1)

Jens
Jens

Reputation: 69450

Add the @Qualifier annotation to the parameter not to the method:

public SomeOtherClass someOtherClass(@Qualifier("classA") InterfaceA object) {...}

Upvotes: 10

Related Questions