一、基于@Component注解的配置
Spring 2.5 中除了提供 @Component 注释外,还定义了几个拥有特殊语义的注释,它们分别是:@Repository、@Service 和 @Controller。
在目前的 Spring 版本中,这 3 个注释和 @Component 是等效的,但是从注释类的命名上,很容易看出这 3 个注释分别和持久层、业务层和控制层(Web 层)相对应。
虽然目前这3 个注释和 @Component 相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能。所以,如果 Web 应用程序采用了经典的三层分层结构的话,最好在持久层、业务层和控制层分别采用上述注解对分层中的类进行注释。
1、@controller 控制器(注入服务)
2、@service 服务(注入dao)
3、@repository dao(实现dao访问)
4、@component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)
@component用法如下:
在类上使用@Component注解,表示该类定义为Spring管理Bean,使用默认value(可选)属性表示Bean标识符。
相当于:
@Component,@Service,@Controller,@Repository注解的类,并把这些类纳入进spring容器中管理。
下面写这个是引入component的扫描组件
其中base-package为需要扫描的包(含所有子包)
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
二、使用实例
User.java:用@Repository注解
UserDao.java
UserDaoImp.java:用@Controller注解
UserService.java:用@Service注解
beans.xml'
测试下:
结果:
当在组件类中使用了特定的注解之后,还需要在Spring的配置文件中声明 <context:component-scan>:
- base-package属性指定一个需要扫描的基类包,Spring容器将会扫描整个基类包里及其子包中的所有类
- 当需要扫描多个包时,可以使用逗号分隔
- 如果仅希望扫描特定的类而非基包下的所有类,可使用resource-pattern属性过滤特定的类,实例:
- <context:include-filter>子节点表示要包含的目标类
- <context:exclude-filter>子节点表示要排除在外的目标类
- <context:component-scan>下可以拥有若干个<context:include-filter>和<context:exclude-filter>子节点
- <context:include-filter>和<context:exclude-filter>子节点支持多种类型的过滤表
三、更多的配置元数据
1、@Lazy:定义Bean将延迟初始化,使用方式如下:
使用@Lazy注解指定Bean需要延迟初始化。
2、@DependsOn:定义Bean初始化及销毁时的顺序,使用方式如下:
3、@Scope:定义Bean作用域,默认单例,使用方式如下:
4、@Qualifier:指定限定描述符,对应于基于XML配置中的<qualifier>标签,使用方式如下:
可以使用复杂的扩展,如@Mysql等等。
5、@Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常,使用方式如下: