前面我们介绍Spring IoC装载的时候,使用XML配置这种方法来装配Bean,这种方法可以很直观的看到每个Bean的依赖,但缺点也很明显:写起来非常繁琐,每增加一个组件,就必须把新的Bean配置到XML中。

有没有更简单的配置方式呢?

有,Spring为我们提供一种可以不依赖XML配置,自动扫描并装配Bean的方法,基于注解的自动挡装配方式。

Spring 通过注解实现自动装配的步骤:

  1. 引入依赖
  2. 开启组件扫描
  3. 使用注解定义 Bean
  4. 依赖注入

1、引入依赖

使用注解的第一步,就是要在项目中引入以下 Jar 包:
org.springframework.core-5.3.13.jar
org.springframework.beans-5.3.13.jar
spring-context-5.3.13.jar
spring-expression-5.3.13.jar
commons.logging-1.2.jar
spring-aop-5.3.13.jar
注意,除了 spring 的四个基础 jar 包和 commons-logging-xxx.jar 外,想要使用注解实现 Spring 自动装配,还需要引入Spring 提供的 spring-aop 的 Jar 包。

2、开启组件扫描

Spring 默认不使用注解装配 Bean,因此需要开启Spring Bean的自动扫描功能,有三种方式:

2.1  XML配置

通过 <context:component-scan> 元素开启 Spring Beans的自动扫描功能。开启此功能后,Spring 会自动从扫描指定的包(base-package 属性设置)及其子包下的所有类,如果类上使用了 @Component 注解,就将该类装配到容器中。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启组件扫描功能-->
<context:component-scan base-package="net.biancheng.c"></context:component-scan>
</beans>

2.2  通过Java配置方式,启动自动扫描功能

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.cn.config")
public class BlogSystemConfig {
/**
* 在这里实现java方式的配置,
*/
}

2.3  SpringBoot中可以利用@SpringBootApplication注解的方式启动自动扫描功能  

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

3、使用注解定义Bean 

Spring 提供以下多个注解,这些注解可以直接标注在Java类上,将它们定义成Spring Bean。

@Component:用于描述 Spring 中的 Bean,它是一个泛化的概念,仅仅表示容器中的一个组件(Bean),并且可以作用在应用的任何层次,例如 Service 层、Dao 层等。使用时只需将该注解标注在相应类上即可。

@Repository: 用于将数据访问层(Dao 层)的类标识为 Spring 中的 Bean,其功能与 @Component 相同。

@Service:通常作用在业务层(Service 层),用于将业务层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。

@Controller:通常作用在控制层(如 Struts2 的 Action、SpringMVC 的 Controller),用于将控制层的类标识为 Spring 中的 Bean,其功能与 @Component 相同。

4、依赖注入

我们可以通过以下注解将定义好 Bean 装配到其它的 Bean 中。

@Autowired

可以应用到 Bean 的属性变量、setter 方法、非 setter 方法及构造函数等,默认按照 Bean 的类型进行装配。

@Autowired 注解默认按照 Bean 的类型进行装配,默认情况下它要求依赖对象必须存在,如果允许 null 值,可以设置它的 required 属性为 false。如果我们想使用按照名称(byName)来装配,可以结合 @Qualifier 注解一起使用

@Resource

作用与 Autowired 相同,区别在于 @Autowired 默认按照 Bean 类型装配,而 @Resource 默认按照 Bean 的名称进行装配。

@Resource 中有两个重要属性:name 和 type。
Spring 将 name 属性解析为 Bean 的实例名称,type 属性解析为 Bean 的实例类型。

  • 如果指定 name 属性,则按实例名称进行装配;
  • 如果指定 type 属性,则按 Bean 类型进行装配;
  • 如果都不指定,则先按 Bean 实例名称装配,如果不能匹配,则再按照 Bean 类型进行装配;如果都无法匹配,则抛出 NoSuchBeanDefinitionException 异常。

@Qualifier

与 @Autowired 注解配合使用,会将默认的按 Bean 类型装配修改为按 Bean 的实例名称装配,Bean 的实例名称由 @Qualifier 注解的参数指定。

5、案例

下面以一个例子说明:

1、创建接口CompactDisc

package soundsystem;

public interface CompactDisc {
void play();
}

 2、创建带有 @Component 注解的 CompactDisc 实现类 SgtPeppers

package soundsystem;

import org.springframework.stereotype.Component;

@Component
public class SgtPeppers implements CompactDisc { private String title = "Sgt. Pepper's Lonely Hearts Club Band";
private String artist = "The Beatles"; public void play() {
System.out.println("Playing " + title + " by " + artist);
} }

 3、启用组件扫描

package soundsystem;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan
public class CDPlayerConfig {
}

 或者配置xml的方式:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="soundsystem" /> </beans>

 4、测试

package soundsystem;

import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest { @Autowired
private CompactDisc cd; @Test
public void cdShouldNotBeNull() {
assertNotNull(cd);
} }

 

参考文献:

http://c.biancheng.net/spring/autowire-annotation.html

https://codeantenna.com/a/q59QIGKYJu

https://potoyang.gitbook.io/spring-in-action-v4/di-2-zhang-zhuang-pei-bean/untitled/2.2.1-chuang-jian-ke-bei-fa-xian-de-bean   《Spring实战(第四版本)》

Spring基于注解自动装配的更多相关文章

  1. Spring操作指南-IoC基础环境配置(基于注解自动装配)

    项目源码:http://code.taobao.org/p/LearningJavaEE/src/LearningSpring001%20-%20Automatically%20wiring%20be ...

  2. Spring 基于注解的装配

    xml头文件 xmlns:context="http://www.springframework.org/schema/context" 扫描包:<context:compo ...

  3. [原创]java WEB学习笔记103:Spring学习---Spring Bean配置:基于注解的方式(基于注解配置bean,基于注解来装配bean的属性)

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  4. Spring学习(六)-----Spring使用@Autowired注解自动装配

    Spring使用@Autowired注解自动装配 在上一篇 Spring学习(三)-----Spring自动装配Beans示例中,它会匹配当前Spring容器任何bean的属性自动装配.在大多数情况下 ...

  5. 【Spring注解驱动开发】使用@Autowired@Qualifier@Primary三大注解自动装配组件,你会了吗?

    写在前面 [Spring专题]停更一个多月,期间在更新其他专题的内容,不少小伙伴纷纷留言说:冰河,你[Spring专题]是不是停更了啊!其实并没有停更,只是中途有很多小伙伴留言说急需学习一些知识技能, ...

  6. Spring 基于注解零配置开发

    本文是转载文章,感觉比较好,如有侵权,请联系本人,我将及时删除. 原文网址:< Spring 基于注解零配置开发 > 一:搜索Bean 再也不用在XML文件里写什么配置信息了. Sprin ...

  7. 【面试普通人VS高手系列】Spring Boot中自动装配机制的原理

    最近一个粉丝说,他面试了4个公司,有三个公司问他:"Spring Boot 中自动装配机制的原理" 他回答了,感觉没回答错误,但是怎么就没给offer呢? 对于这个问题,看看普通人 ...

  8. Spring基于注解的Cache支持

    Spring为我们提供了几个注解来支持Spring Cache.其核心主要是@Cacheable和@CacheEvict.使用@Cacheable标记的方法在执行后Spring Cache将缓存其返回 ...

  9. Spring(六)之自动装配

    一.自动装配模型 下面是自动连接模式,可以用来指示Spring容器使用自动连接进行依赖注入.您可以使用元素的autowire属性为bean定义指定autowire模式. 可以使用 byType 或者  ...

随机推荐

  1. 逆置单链表(基于c语言)

    直接插入全部代码:(reverseLinklist函数是逆置操作) #include <stdio.h> #include <stdlib.h> #include <as ...

  2. petite-vue源码剖析-逐行解读@vue/reactivity之reactive

    在petite-vue中我们通过reactive构建上下文对象,并将根据状态渲染UI的逻辑作为入参传递给effect,然后神奇的事情发生了,当状态发生变化时将自动触发UI重新渲染.那么到底这是怎么做到 ...

  3. CentOS停更;阿里发布全新操作系统(Anolis OS)

    镜像下载.域名解析.时间同步请点击阿里云开源镜像站 Linux系统对于Java程序员来说,就好比"乞丐手里的碗",任何业务都离不开他的身影,因为服务端的广泛使用,也因此衍生出了各种 ...

  4. centos7升级openssh8.7&openssl1.1.1l脚本

    脚本下载地址或首页联系本人获取 https://files.cnblogs.com/files/blogs/705493/update_ssh.sh 需搭配openssh8.7和openssl1.1. ...

  5. Windows10运行Cura源代码,搭建环境教程

    参考官方文档 https://github.com/Ultimaker/Cura/wiki/Running-Cura-from-Source-on-Windows#python-3810 注意 这些说 ...

  6. ChIP-seq技术介绍|易基因

    大家好,这里是专注表观组学十余年,多组学科研服务领跑者的易基因. 染色质免疫沉淀后测序(ChIP seq)是一种针对DNA结合蛋白.组蛋白修饰或核小体的全基因组分析技术.由于二代测序技术的巨大进步,C ...

  7. du 和 df 的定义,以及区别?

    du 显示目录或文件的大小 df 显示每个<文件>所在的文件系统的信息,默认是显示所有文件系统.(文件系统分配其中的一些磁盘块用来记录它自身的一些数据,如 i 节点,磁盘分布图,间接块,超 ...

  8. 为什么枚举单例在 Java 中更好?

    枚举单例是使用一个实例在 Java 中实现单例模式的新方法.虽然Java中的单例模式存在很长时间,但枚举单例是相对较新的概念,在引入Enum作为关键字和功能之后,从Java5开始在实践中.本文与之前关 ...

  9. 什么是 Swagger?你用 Spring Boot 实现了它吗?

    Swagger 广泛用于可视化 API,使用 Swagger UI 为前端开发人员提供在线沙箱.Swagger 是用于生成 RESTful Web 服务的可视化表示的工具,规范和完整框架实现.它使文档 ...

  10. java常用方法集合

    1.获取当前日期 // 获取当前日期 public Date getDate(int num) { Calendar cal = new GregorianCalendar(); cal.setTim ...