![](/img/trans.png)
[英]Spring boot consider defining a bean of type, component scan not working
[英]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.