本文介绍了在 Spring 3 中组织类以进行组件扫描的聪明方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用 Spring 3 开发一个新项目,并且我正在使用注释.我喜欢我可以连接我的类来注入依赖项,但我知道让 context: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.

我正在使用一个 DispatcherServlet,它有自己的 xml 配置文件.这也是一个 context:component-scan.当我第一次开始学习 Spring 时,我的组件扫描中有重叠,并且看到了多次创建的 bean.我想避免这种情况.

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.

有什么好方法可以组织我的包或组件扫描以覆盖所有 bean 而不会重复?

What is a good way to organize either my packages or my component scans to cover all the beans without duplication?

目前我有这样的包:

my.package.controller
my.package.dao
my.package.entity
my.package.service
my.package.util

如果我在所有这些包中都有 bean,那么简单的方法似乎是把 <context:component-scan base-package="my.package"></context:component-scan> 进入 applicationContext.xml 并完成.

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.

扫描调度程序的xml中的my.package.controller和applicationContext.xml中的其余部分(不包括my.package.controller)会更好吗?

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

我正在使用 @Autowired 将日志记录添加到我的大部分类(如果不是全部的话),所以我不知道我会有任何不会被注释的类.

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.

谢谢!

推荐答案

是的 - 在您的主要上下文中扫描除控制器之外的所有内容

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>

在您的 DispatcherServlet 上下文中,只需扫描控制器包.

and in your DispatcherServlet context just scan the controller package.

这篇关于在 Spring 3 中组织类以进行组件扫描的聪明方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 09:07
查看更多