其他分享
首页 > 其他分享> > 春季启动:测试和主要之间的NoUniqueBeanDefinitionException

春季启动:测试和主要之间的NoUniqueBeanDefinitionException

作者:互联网

我有一个SpringBoot main / Application.java类

@SpringBootApplication
@ComponentScan(value = "com.nfl.dm.shield", excludeFilters =
        {
                @ComponentScan.Filter(value = MemoryRepository.class, type = FilterType.ASSIGNABLE_TYPE)
        }
)
public class Application {

    final static Logger LOG = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        LOG.info("Booting application...");
        SpringApplication.run(Application.class, args);
    }
}

和一个类似的测试

@Configuration
@ComponentScan(basePackages = {"com.nfl.dm.shield"}, excludeFilters =
        {
                @ComponentScan.Filter(value = MySqlRepository.class, type = FilterType.ASSIGNABLE_TYPE)
        }
)
public class ApplicationTestConfig {
}

主代码正确运行.测试代码引发NoUniqueBeanDefinitionException,似乎没有正确过滤掉不需要的MySqlRepository组件.

解决方法:

经过一天多的尝试以多种方式排除不需要的bean,核心问题是@ComponentScan同时拉入Application和ApplicationTest,从而导致对Application的附加扫描,从而导致加载了不需要的服务.

解决方法,添加:

                @ComponentScan.Filter(value = Application.class, type = FilterType.ASSIGNABLE_TYPE)

到ApplicationTestConfig.java中的列表.因此,在加载ApplicationTestConfig并触发组件扫描时,它将忽略Application(以及所有Application的特定配置).

标签:spring-boot,testing,component-scan,spring
来源: https://codeday.me/bug/20191120/2041383.html