What's a smart way to organize classes in Spring 3 for component-scan?
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!
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.
精彩评论