繁体   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