Spring boot ComponentScan excludeFIlters not excluding

前端 未结 2 480
栀梦
栀梦 2021-02-05 12:37

I am having a SimpleTest :

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SimpleTestConfig.class)
public class SimpleTest {
    @Test
           


        
相关标签:
2条回答
  • 2021-02-05 13:03

    You can define custom component scan filter for excluding it.

    Example code will be like:

    @SpringBootApplication()
    @ComponentScan(excludeFilters=@Filter(type = FilterType.REGEX, pattern="com.wyn.applications.starter.Starter*"))
    public class SimpleTestConfig {
    
    }
    

    This works for me.

    For further reading go to this blog.

    0 讨论(0)
  • 2021-02-05 13:22

    Each component scan does filtering individually. While you exclude Starter.class from SimpleTestConfig, SimpleTestConfig initializes Application, which does it's own @ComponentScan without excluding Starter. The clean way of using ComponentScan is for each ComponentScan to scan separate packages, that way each filter works fine. When 2 separate ComponentScans scan the same package (as in your tests), this does not work.

    One way to trick this is to provide a mock Starter bean:

    import org.springframework.boot.test.mock.mockito.MockBean;
    
    public class SimpleTest {
        @MockBean
        private Starter myTestBean;
        ...
    }
    

    Spring will use that mock instead of the real class, thus the @PostConstruct method will not be called.

    Other common solutions:

    • Do not directly use Application.class in any unit test
    • Use Spring profile and annotations such as @Profile("!TEST") on the Starter class
    • Use a spring Boot @ConditionalOn... annotation on the Starter class
    0 讨论(0)
提交回复
热议问题