Spring依赖注入(基于注解Annotation)

在Spring中,尽管使用XML配置文件可以实现Bean的装配工作,但如果应用中有很多Bean时,会导致 XML 配置文件过于臃肿,给后续的维护和升级工作带来一定的困难。为此,Spring提供了对Annotation(注解) 技术的全面支持。

常用的注解

1)作用在类上(@Component组件)

Spring中提供@Component的三个衍生注解:(功能目前来讲是一致的)

  • @Controller :WEB层
  • @Service: 业务层
  • @Repository:持久层

这三个注解是为了让标注类本身的前途清晰,Spring在后续版本会对其增强。

2)属性注入的注解(可以不用提供set方法)

  • @Value:用于注入普通类型
  • @Autowired:自动装配
    —— 默认按类型进行装配
    —— 按名称注入:@Qualifier:强制使用名称注入
  • @Resource 相当于:@Autowired和@Qualifier 一起使用

3)Bean的作用范围的注解

@Scope:有singleton单例、prototype多例

4)Bean的生命周期配置

  • @PostContruct:相当于init-method
  • @PreDestroy:相当于destory-method

XML与注解的比较

07Spring - Spring依赖注入(基于注解Annotation)_# Spring

注解的使用流程

下载、导包的步骤略。

1)xml配置注解扫描
07Spring - Spring依赖注入(基于注解Annotation)_# Spring_02

2)相关类添加注解
07Spring - Spring依赖注入(基于注解Annotation)_# Spring_03

3)编写测试类测试
07Spring - Spring依赖注入(基于注解Annotation)_# Spring_04