Spring [IoC]6 详解@Autowired、@Qualifier和@Required

本文详细介绍了Spring框架中的@Autowired、@Qualifier和@Required三个注解的用途和用法。@Autowired用于自动装配依赖,支持字段、构造函数和方法;@Qualifier则提供更精确的依赖选择,当有多个相同类型的bean时,可以指定具体bean的名称;@Required注解确保setter方法必须被配置以依赖注入。文章通过实例展示了这三个注解在数组、Set、Map等不同场景的应用。
摘要由CSDN通过智能技术生成

A、@Autowired

org.springframework.beans.factory.annotation.Autowired

public @interface Autowired

Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.

标注一个构造函数,字段,setter方法或者配置方法,让它通过spring的依赖注入方法自动装填。

 

Only one constructor (at max) of any given bean class may carry this annotation, indicating the constructor to autowire when used as a Spring bean. Such a constructor does not have to be public.

任何一个给定的bean类只能有一个构造函数可以携带这个注释,表示这个类作为一个spring的bean使用时,这个构造器将用于自动装配。这个构造函数不是必须是public。

 

Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public.

在一个bean创建之后,任何方法被调用之前,这个字段被注入。这个字段不是必须是public。

 

Config methods may have an arbitrary name and any number of arguments; each of those arguments will be autowired with a matching bean in the Spring container. Bean property setter methods are effectively just a special case of such a general config method. Such config methods do not have to be public.

配置方法它可以是任意名称和有任意多个参数。这个方法的任何一个参数都将使用spring容器中匹配的bean来自动装填。Bean属性的setter方法也是有效的,它是普通的配置方法的一个特例。配置方法不是必须是public。

 

In the case of multiple argument methods, the 'required' parameter is applicable for all arguments.

当有多个参数的方法情况下,'required'将适用于所有参数。

 

In case of a Collection or Map dependency type, the container will autowire all beans matching the declared value type. In case of a Map, the keys must be declared as type String and will be resolved to the corresponding bean names.

Collection或Map依赖类型情况,容器将自动装配bean匹配声明的值类型,这个Map的key必须是String,Map的values必须是已知的类型。

 

属性

boolean required

Declares whether the annotated dependency is required.

Defaults to true.

声明这个注释依赖是否需要,默认是true。

 

A.1、数组、Set、Map

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值