簡體   English   中英

spring boot - 從組件掃描中排除 bean 不起作用

[英]spring boot - exclude bean from component scan does not work

這個 spring boot 項目中,一個集成測試創建了一個 spring 應用程序上下文,它應該創建所有必需的 bean,除了那些帶有@ExcludeFromTests注釋的 bean

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest(classes=IntegrationTestApplication.class, 
                webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class IntegrationTest_CartController 
{
     /*....*/
}

測試應用加載一個@Configuration

@Profile("test")
@Configuration
@ComponentScan(basePackages = {"com.example.demo", "com.example.demo.*"}, 
               excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, 
                                                      value = ExcludeFromTests.class))
@EnableJpaRepositories("com.example.demo.dao")
@EntityScan("com.example.demo.resource")
@EnableAutoConfiguration
public class TestDemoAppConfig 
{
    private static final Logger LOG = LoggerFactory.getLogger(TestDemoAppConfig.class);

    public TestDemoAppConfig()
    {
        // I can see this being printed out
        LOG.info("_________________________________");
        LOG.info("Instantiating TestDemoAppConfig");
        LOG.info("_________________________________");
    }
}

也就是說,它在com.example.demo包中加載 bean,但應該忽略那些用@ExcludeFromTests注釋的,例如

@Component
@ExcludeFromTests
public class ItemDaoInit 
{
    private static final Logger LOG = LoggerFactory.getLogger(ItemDaoInit.class);

    public ItemDaoInit(@Autowired ItemDao dao)
    {
        init(dao);
    }

    private void init(ItemDao dao)
    {
       LOG.info(" ------------ item dao preprocessor called"); // I shouldn't see this when I run a test as this bean shouldnt be created
       /* preprocess entries in dao */
    }
 }

當我運行應用程序時,我可以看到加載了正確的@Configuration但仍然創建了ItemDaoInit bean

""2018-02-28 11:54:28 [main] INFO  com.example.demo.dao.ItemDaoInit -  ------------ item dao preprocessor called

為什么會創建這個 bean,盡管它帶有我明確排除在組件掃描之外的注釋?

編輯

順便說一句,如果我從上面的測試配置類中排除@EnableAutoConfiguration問題仍然存在

編輯 2

這是IntegrationTestApplication 它只是掃描@Configuration

@SpringBootApplication
@ComponentScan(basePackageClasses= {TestDemoAppConfig.class})
public class IntegrationTestApplication 
{
    public static void main(String[] args) {
        SpringApplication.run(IntegrationTestApplication.class, args);
    }
}

謝謝您的幫助

剛剛在我的項目中解決了同樣的問題。 @ComponentScan在注釋IntegrationTestApplication沒有excludeFilters聲明,其實你有辦法2個獨立的重疊@ComponentScan宣言和應用程序加載的一個,從包裝的所有豆類TestDemoAppConfig.class即使從2一個TestDemoAppConfig排除。

您必須最好在應用程序類中保留唯一一個@ComponentScan注釋(聲明了excludeFilters ),因為默認情況下@SpringBootApplication隱式添加了使用類包的組件掃描。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM