org.springframework.beans.factory.NoUniqueBeanDefinitionException
阿新 • • 發佈:2020-08-11
公司把基礎的類,打成了一個boot-starter的包,引入到新專案不是太好維護,當新寫一個mapper進行基礎的時候,就會報錯
org.springframework.beans.factory.NoUniqueBeanDefinitionException異常資訊
解決:加上@Primary註解。
官網說明如下:
Fine-tuning Annotation-based 使用 @Primary 自動裝配
由於按型別自動裝配可能會導致多個候選項,因此通常需要對選擇 process 進行更多控制。實現此目的的一種方法是使用 Spring 的@Primary
annotation。 @Primary
請考慮以下 configuration 將firstMovieCatalog
定義為主MovieCatalog
:
@Configuration public class MovieConfiguration { @Bean @Primary public MovieCatalog firstMovieCatalog() { ... } @Bean public MovieCatalog secondMovieCatalog() { ... } // ... }
使用前面的 configuration,以下MovieRecommender
與firstMovieCatalog
一起自動裝配:
public class MovieRecommender {
@Autowired
private MovieCatalog movieCatalog;
// ...
}
相應的 bean 定義如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <bean class="example.SimpleMovieCatalog" primary="true"> <!-- inject any dependencies required by this bean --> </bean> <bean class="example.SimpleMovieCatalog"> <!-- inject any dependencies required by this bean --> </bean> <bean id="movieRecommender" class="example.MovieRecommender"/> </beans>