Spring——注解实现自动装配

使用注解须知:

  1. 导入约束:context约束

  2. 配置注解的支持:context:annotation-config

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"
	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

直接在属性上使用即可,也可以在set方式上使用

使用Autowired时,可以不用编写set方法,前提是自动装配的属性在ioc(Spring)容器中存在,且符合名字byname!

测试代码:

java 复制代码
public class People {

    // 如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    private Cat cat;
    @Autowired
    private Dog dog;
    private String name;
}

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value="xxx")去配合@Autowired的使用,指定一个唯一的bean对象注入。

java 复制代码
public class People {

    // 如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired(required = false)
    @Qualifier(value = "cat111")
    private Cat cat;
    
    @Autowired
    @Qualifier(value = "dog222")
    private Dog dog;
    private String name;
相关推荐
xurileidian30 分钟前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python
NEIL_XU_1 小时前
自研提效工具——Bug通:打通测试与开发的「最后一公里」
后端·ai编程
Mikko72 小时前
Redis 主从切换期间可用吗?6.2 实测哨兵切换:应用不可写 33 秒,主从连不上、数据不一致,以及设了 ACL 后哨兵不切换
java·运维·redis·后端
猿人谷2 小时前
从百万个 Pareto 解中选出 100 个:Riesz s-Energy 如何实现高效的多样性选择?
后端·算法·aigc
不积跬步无以至千里mmbb262 小时前
【软件工艺师 rust相关课程】
开发语言·后端·rust
不得了zz2 小时前
11-Agent 可观测与评估:Spring AI Alibaba Admin Studio 到底解决了什么
java·人工智能·后端·spring·ai编程·springaialibaba
软件技术NINI2 小时前
基于 SpringBoot 的酒店预定系统
java·spring boot·后端
利威尔xu2 小时前
Go context取消传播3层:信号传不到第3层goroutine,泄漏拖垮
后端·golang
软件技术NINI2 小时前
基于 Spring Boot 中国历史知识学习系统
spring boot·后端·学习