Spring注解实现Bean自动装配示例详解
何为自动装配
自动装配是 Spring 满足 bean 依赖的一种方式。
在使用 Spring 配置 bean 时,我们都要给配置的 bean 的属性设置一个值,如果不手动设置则都是空。而自动的好处就在于,我们不用手动去设置一个值,spring 会在上下文中自动寻找并装配合适的值。
本文主要介绍了Spring注解Bean自动装配的相关内容,下面话不多少了,来一起看看详细的介绍吧
使用须知:
1.导入约束:context约束
2.配置注解的支持: context:annotation-config/
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> </beans>
@Autowired
通过ByType的方式实现自动装配,且必须要求该对象存在。
直接在属性上使用,也可以在set方法上使用。
使用Autowired时,可以不用编写set方法,前提是你这个自动装配的属性在IOC容器中存在,且符合Byname方式
@Autowired private Cat cat;
@Qualifier
@Autowired @Qualifier(value = "dog111") private Dog dog;
如果@Autowired自动装配的环境比较复杂,可以使用@Qualifier来辅助@Autowired完成自动装配,
通过@Qualifier(value = “dog111”)指定Bean的ID来装配。
总结
到此这篇关于Spring注解实现Bean自动装配的文章就介绍到这了,更多相关Spring注解Bean自动装配内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
关于Spring3 + Mybatis3整合时多数据源动态切换的问题
这篇文章主要介绍了关于Spring3 + Mybatis3整合时多数据源动态切换的问题,需要的朋友可以参考下2017-04-04
SQL Server 2000 Driver for JDBC Service Pack 3 安装测试方法
这篇文章主要介绍了数据库连接测试程序(SQL Server 2000 Driver for JDBC Service Pack 3 安装测试),需要的朋友可以参考下2014-10-10
SpringBoot配置SwaggerUI访问404错误的解决方法
这篇文章主要为大家详细介绍了SpringBoot配置SwaggerUI访问404错误的解决方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-12-12
SpringBoot 启动报错Unable to connect to 
这篇文章主要介绍了SpringBoot 启动报错Unable to connect to Redis server: 127.0.0.1/127.0.0.1:6379问题的解决方案,文中通过图文结合的方式给大家讲解的非常详细,对大家解决问题有一定的帮助,需要的朋友可以参考下2024-10-10


最新评论