Shadi
Shadi

Reputation: 557

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

I'm maintaining a project with two set of main packages, the project is using Spring and Spring MVC, one of these packages contains several controllers and is scanned using XML configuration (<context:component-scan />).

The problem is that there is a single class in the other package (not scanned), and I need this class to be scanned, but only this class and nothing else in the package. I can't change its package now since it would be too risky now.

So is there a way to do this using annotations or XML ?

Upvotes: 35

Views: 36235

Answers (4)

Robert Hunt
Robert Hunt

Reputation: 8354

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)

Upvotes: 23

Emerson Farrugia
Emerson Farrugia

Reputation: 11363

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)
    })

Upvotes: 65

Bart
Bart

Reputation: 17371

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

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

Upvotes: 23

Pratik Shelar
Pratik Shelar

Reputation: 3212

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>

Upvotes: -3

Related Questions