问题
Can I get Spring to throw an exception when there is more than one bean with the same type? The current behavior seems to be to inject null
.
回答1:
You need to use the @Qualifier
annotation together with @Annotated
to resolve ambiguity between different beans with the same type. The parameter to Qualified is the name of the bean, which is automatically set based on the name of the method that is annotated with @Bean
.
@Autowired public RobotController (@Qualifier("gundam") RobotEngine robotEngine)
You can also set a custom name or qualifier when declaring a bean using @Bean(name="myName")
or @Bean @Qualifier("myName")
. The annotation @Primary
can be used to set one of the beans as the "default" if no qualifier is specified. You can also create custom annotations that inherit from Qualifier, to make code a little prettier.
Read the Spring docs on autowiring, in particular section 6.9.4.
回答2:
You should get an error, yes.
From http://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/beans.html#beans-factory-autowire:
Multiple bean definitions within the container may match the type specified by the setter method or constructor argument to be autowired. For arrays, collections, or Maps, this is not necessarily a problem. However for dependencies that expect a single value, this ambiguity is not arbitrarily resolved. If no unique bean definition is available, an exception is thrown.
You should get a runtime exception with an error like:
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [...] is defined: expected single matching bean but found 2: ...
来源:https://stackoverflow.com/questions/32245003/will-spring-throw-an-exception-if-there-is-ambiguity-when-resolving-a-bean