Exclude-filter for a @Component class while JUnit

2019-05-10 20:10发布

问题:

is it possible to exclude a @Component annotated class?

i would like to exclude a special class from JUnit testing.

my project has a class xEventHandler annotated with @Component and i dont want spring to use this class while junit testing.

my ApplicationTestContext.xml looks like this:

<context:component-scan base-package="com.company">
...
<context:exclude-filter expression="com\.company\.xyz\.xEventHandler.java " type="regex"/>
...
</context:component-scan>

however, the class gets entered because of the @Component annotation(e.g. works, when i delete the @Component from that class).

how can i fix it?

回答1:

I think it should just be:

<context:exclude-filter expression="com\.company\.xyz\.xEventHandler" type="regex"/>


回答2:

IMHO it is better to use profiles (introduced in 3.1) to achieve this:

  • define this bean inside test profile
  • activate test profile in JUnit test by adding @ActiveProfiles("test") annotation

More information about profiles:

  • http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/
  • http://www.captaindebug.com/2012/08/using-spring-profiles-in-xml-config.html