Using @ComponentScan or <context:component-scan /> with only one class

谁说胖子不能爱 提交于 2019-11-28 09:39:15

Simply add is as a bean to your context e.g.

<bean class="my.package.MyClass" />

What @Bart said for XML.

If you need to pull in that one class using annotations, add the following to one of your @Configuration classes

@ComponentScan(
    basePackageClasses = YourClass.class, 
    useDefaultFilters = false,
    includeFilters = {
        @ComponentScan.Filter(type = ASSIGNABLE_TYPE, value = YourClass.class)
    })

In addition to the method described by Emerson Farrugia there is a less verbose solution which has been supported since Spring Framework 4.2 as mentioned in the documentation here.

As of Spring Framework 4.2, @Import also supports references regular component classes, analogous to the AnnotationConfigApplicationContext.register method. This is particularly useful if you want to avoid component scanning, by using a few configuration classes as entry points to explicitly define all your components.

So your example would simply become:

@Import(YourClass.class)

You need to use filters to filter out other classes and just include your class which you want to be scanned

<context:component-scan base-package="com.abc" >

    <context:include-filter type="regex" 
                   expression="com.abc.customer.dao.*DAO.*" /> 

</context:component-scan>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!