您的位置:首页 > 编程语言 > Java开发

spring 自动检测bean

2015-08-03 16:16 375 查看
当在spring配置中增加<context:annotation-config>时,我们希望spring特殊对待我们所定义的bean里的某一组注解,并使用这些注解指导bean装配。即使<context:anntation-config>有助于完全消除spring配置中的<property>和<constructor-arg>元素,我们仍需要使用<bean>元素显示定义bean。

但是spring还有另一种技巧。<context:component-scan>元素除了完成与<context:annotation-config>一样的工作,还允许spring自动检测bean和定义bean,这意味着bean不使用<bean>元素,spring应用中的大多数bean都能够实现定义和装配。

为了配置spring自动检测,需要使用<context:component-scan>元素来代替<context:annotation-config>元素。base-package属性标识了<context:component-scan>元素所扫描的包。

。为自动检测标注bean

默认情况下,<context:component-scan>查找使用构造型(stereotype)注解所标注的类,这些特殊的注解如下。

@Component-通用的构造型注解,标识该类为spring的组件,

@Controller-标识将该类定义为 Spring MVC controller.

@Repository-标识将该类定义为数据仓库。

@Service-标示将该类定义为服务。

使用@Component标注的任意自定义注解。

例如,假设我们的应用上下文中仅仅包含eddie和guitar两个bean。可以配置<context:component-scan>元素并使用@Component注解标注Instrumentalist和Guitar类,从而消除显示的<bean>定义。

package com.springinaction.springidol;

@Component

public class Guitar implements Instrument{

}

spring扫描com.springinaction.springidol包时,会发现使用@Component注解所标注的Guitar,并自动地将 他注册为Spring Bean.Bean的Id默认为无限定类名。在这种情景下,Guitar Bean的Id为guitar.

package com.springinaction.springidol;

@Component("eddie")

public class Instrumentalist implements Performer{

}

在这种场景下,我们指定了一个Bean Id作为@Component注解的参数。该Bean的Id不会像上一个示例中那样默认设置为类的名称"Instrumentalist",而是显示命名为eddie。

当使用<context:component-scan>时,基于注解地自动检测只是一种扫描策略。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: