I've begun work on a new project using Spring 3 and I'm using annotations. I love that I can wire up my classes to get dependencies injected, but I know it's a bad practice to have context:component-scan
start at the base package.
I'm using a DispatcherServlet
which has its own xml configuration file. In that is also a context:component-scan
. When I first started learning Spring I had overlap in my component scans and saw beans created multiple times. I'd like to avoid that.
What is a good way to organize either my packages or my component scans to cover all the beans without duplication?
Currently I have packages like this:
my.package.controller
my.package.dao
my.package.entity
my.package.service
my.package.util
If I have beans in all those packages then it seems like the easy way out would be to put <context:component-scan base-package="my.package"></context:component-scan>
into applicationContext.xml and be done with it.
Would it be better to scan my.package.controller
in the dispatcher's xml and the rest (excluding my.package.controller) in applicationContext.xml?
Or should I arrange all my annotated classes in one area and everything else in another? Something like:
my.package.spring.controller
my.package.spring.dao
my.package.spring.entity
my.package.spring.service
my.package.spring.util
my.package.notannotated
my.package.notannotated2
I'm using @Autowired to add logging to most if not all of my classes so I don't know that I'll have any classes that won't be annotated.
I hate getting stuck on configuration...I'd rather be stuck in code, so if someone can offer any tips I'd readily welcome them.
Thanks!
Using @ComponentScan in a Spring Application. With Spring, we use the @ComponentScan annotation along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.
A Classpath scanning basically means, detecting the classes that need to be managed by the Spring under a specified package. You need to make use of the spring @ComponentScan annotation with the @Configuration for classpath scanning.
A good practice is to explicitly import a @Configuration class with the @Import annotation and add the @ComponentScan annotation to that configuration class to auto-scan only the package of that class.
To add many packages to Component Scan, you should pass the String[] array to the @ComponentScan annotation.
Yes - in your main context scan everything except controllers
<context:component-scan base-package="my.package">
<context:exclude-filter type="regex" expression="my\.package\.controller.*"/>
</context:component-scan>
and in your DispatcherServlet context just scan the controller package.
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