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>
原文地址:https://www.cnblogs.com/dalianpai/p/13473991.html