加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

java – Spring @Autowired for setter方法与非setter方法

发布时间:2020-12-15 01:42:47 所属栏目:大数据 来源:网络整理
导读:根据@Autowired javadoc: Marks a constructor,field,setter method or config method as to be autowired by Springs dependency injection facilities. Only one constructor (at max) of any given bean class may carry this annotation,indicating the

根据@Autowired javadoc:

Marks a constructor,field,setter method or config method as to be autowired
by Spring’s dependency injection facilities. 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. 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. 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.
In the case of multiple argument methods,the ‘required’ parameter is
applicable for all arguments. 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. Note
that actual injection is performed through a BeanPostProcessor which
in turn means that you cannot use @Autowired to inject references into
BeanPostProcessor or BeanFactoryPostProcessor types. Please consult
the javadoc for the AutowiredAnnotationBeanPostProcessor class (which,
by default,checks for the presence of this annotation).

我的问题是:

>配置方法是什么意思?
>而且,假设我有@Autowired的setter方法和@Autowired的一些任意方法.我假设在bean实例化之后,spring会自动调用setter方法,而不会调用随机命名的@Autowired方法,对不对?
> Spring如何理解在实例化(setter)之后应该调用哪个@Autowired方法,而其他人不应该?这与javadoc的声明有何关联,并说:

Bean property setter methods are effectively just a special case of
such a general config method

最后一个问题:我可以在哪里阅读它?因为spring文档没有关于它的任何信息,我无法在其javadoc中找到spring使用的确切逻辑.

最佳答案
@Autowired注释可以与构造函数,setter方法或任何其他方法一起使用.
每当Spring发现@Autowired注释时,它将尝试查找与方法参数匹配的bean,并将调用该方法.如果多个方法(setter或non-setter)具有@Autowired注释,则所有将在bean实例化后由Spring调用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读