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 ?
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.
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.
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.
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) })
Simply add is as a bean to your context e.g.
<bean class="my.package.MyClass" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With