nflearl
nflearl

Reputation: 131

Spring Boot: NoUniqueBeanDefinitionException between test and main

I have a SpringBoot main/Application.java class

@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);
    }
}

and a similar one for Test

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

The main code runs correctly. The test code throws NoUniqueBeanDefinitionException, appearing to not properly filter out the unwanted MySqlRepository component.

Upvotes: 3

Views: 2115

Answers (1)

nflearl
nflearl

Reputation: 131

After over a day of trying many different ways to exclude the unwanted bean, the core issue turned out to be the fact that @ComponentScan was pulling in both Application and ApplicationTest, resulting in an additional scan for Application, resulting in the unwanted service being loaded.

The solution, add:

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

to the list in ApplicationTestConfig.java. So, when ApplicationTestConfig is loaded and triggers the component scan, it ignores Application (and all of Application's specific configurations).

Upvotes: 3

Related Questions