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;
相关推荐
郭萌6965 分钟前
Docker 安装陀螺匠教程
后端
Moso_Rx7 分钟前
JavaEE——线程安全
java·安全·java-ee
u01037310614 分钟前
Django REST Framework (DRF)
后端·python·django
资讯分享周14 分钟前
破局遗留系统!AI自动化重构:从静态方法到Spring Bean注入实战
spring·重构·自动化
牛马喜喜22 分钟前
sequelize的进阶使用(助力成为优秀全栈)
后端·node.js
勇敢牛牛_29 分钟前
【Rust基础】使用Rocket构建基于SSE的流式回复
开发语言·后端·rust
岁岁岁平安30 分钟前
SpringMVC入门学习总结(2025.04.16)
java·spring·java-ee·mvc·springmvc
日月星辰Ace1 小时前
@JsonProperty 用于构造方法和属性
java
Anarkh_Lee1 小时前
解决 Spring Boot 多数据源环境下事务管理器冲突问题(非Neo4j请求标记了 @Transactional 尝试启动Neo4j的事务管理器)
spring boot·后端·spring
Yharim1 小时前
微服务项目相同nacos地址导致的问题
后端·微服务