Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 924
Shadi Avatar asked Jan 09 '14 13:01

Shadi


People also ask

How do I scan a specific class in Spring boot?

We use the @ComponentScan annotation along with the @Configuration annotation to tell Spring to scan classes that are annotated with any stereotype annotation. The @ComponentScan annotation provides different attributes that we can modify to get desired scanning behavior.

What is the purpose of using @ComponentScan in the class files?

The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan.

How do I use context component scan?

Put this “ context:component ” in bean configuration file, it means, enable auto scanning feature in Spring. The base-package is indicate where are your components stored, Spring will scan this folder and find out the bean (annotated with @Component) and register it in Spring container.


2 Answers

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)     }) 
like image 197
Emerson Farrugia Avatar answered Sep 29 '22 03:09

Emerson Farrugia


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

<bean class="my.package.MyClass" /> 
like image 39
Bart Avatar answered Sep 29 '22 02:09

Bart