• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
山高我为峰
博客园    首页    新随笔    联系   管理    订阅  订阅
Spring组件扫描<context:component-scan/>使用详解
<context:component-scan base-package="com.vrv.paw.dao,com.vrv.paw.service,com.vrv.paw.action,install,com.vrv.paw.utils" />

或

<!-- 注解注入 -->
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.vrv.paw.dao" />
<context:component-scan base-package="com.vrv.paw.service" />
<context:component-scan base-package="com.vrv.paw.action" />
<context:component-scan base-package="com.vrv.paw.utils" />
<context:component-scan base-package="install" />
@Component
@Scope("prototype")
public class TreeUtil{
.....
}

如果不想在xml文件中配置bean,我们可以给我们的类加上spring组件注解,然后再配置下spring的扫描器就可以实现bean的自动载入。

原理:
 Spring 2.5引入了更多典型化注解(stereotype annotations): @Component、@Service和 @Controller。
@Component是所有受Spring管理组件的通用形式;而@Repository、@Service和 @Controller则是@Component的细化,用来表示更具体的用例(例如,分别对应了持久化层、服务层和表现层)。
也就是说,你能用@Component来注解你的组件类,但如果用@Repository、@Service 或@Controller来注解它们,你的类也许能更好地被工具处理,或与切面进行关联。
例如,这些典型化注解可以成为理想的切入点目标。
当然,在Spring Framework以后的版本中,@Repository、@Service和 @Controller也许还能携带更多语义。如此一来,如果你正在考虑服务层中是该用@Component还是@Service,那@Service显然是更好的选择。同样的,就像前面说的那样,@Repository已经能在持久化层中进行异常转换时被作为标记使用了。
 
如果有了<context:component-scan>,那么<context:annotation-config/>标签 可以移除掉,因为它被<context:component-scan>包含进去了。
 
<context:component-scan>提供两个子标签:<context:include-filter>和<context:exclude-filter>各代表引入和排除的过滤。
<context:component-scan base-package="com.xhlx.finance.budget" >
  <context:include-filter type="regex" expression=".service.*"/>
</context:component-scan>

 

posted on 2015-12-21 15:37  山高我为峰  阅读(1260)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3