org.springframework.beans.factory.NoUniqueBeanDefinitionException


公司把基礎的類,打成了一個boot-starter的包,引入到新項目不是太好維護,當新寫一個mapper進行基礎的時候,就會報錯

org.springframework.beans.factory.NoUniqueBeanDefinitionException異常信息

解決:加上@Primary注解。

官網說明如下:

Fine-tuning Annotation-based 使用 @Primary 自動裝配

由於按類型自動裝配可能會導致多個候選項,因此通常需要對選擇 process 進行更多控制。實現此目的的一種方法是使用 Spring 的@Primary annotation。 @Primary表示當多個 beans 是自動連接到 single-valued 依賴項的候選者時,應該優先選擇特定的 bean。如果候選者中只存在一個主 bean,則它將成為自動連接的 value。

請考慮以下 configuration 將firstMovieCatalog定義為主MovieCatalog

@Configuration
public class MovieConfiguration {

    @Bean
    @Primary
    public MovieCatalog firstMovieCatalog() { ... }

    @Bean
    public MovieCatalog secondMovieCatalog() { ... }

    // ...
}

使用前面的 configuration,以下MovieRecommenderfirstMovieCatalog一起自動裝配:

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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM