【问题标题】:Spring @Autowire on non-setter methodsSpring @Autowire on non-setter 方法
【发布时间】:2017-06-07 10:36:31
【问题描述】:

我刚刚遇到了一些在非 setter 方法上使用 @Autowire 的示例。

@Autowired
public void doSomething(MyType t){
     System.out.println(t);
}
  1. 我将如何调用此方法?像 objectReference.doSomething();调用这些方法时不需要参数吗?
  2. 我们什么时候在非 setter 方法上使用 @Autowire
  3. 任何人都可以分享一些相同的样本吗?

【问题讨论】:

标签: java spring autowired


【解决方案1】:

spring doc 明确表示,@Autowired 可以应用于具有任意名称和/或多个参数的构造函数、字段、设置器和任意方法。

提出你的问题,想想doSomething(<>) 是一个任意方法,它应该由容器而不是你自己调用。 Have a look at this thread

【讨论】:

  • 是的,必须由容器控制,名称可以是任何东西。
【解决方案2】:
@Target(value={CONSTRUCTOR,METHOD,PARAMETER,FIELD,ANNOTATION_TYPE})
 @Retention(value=RUNTIME)
 @Documented
public @interface Autowired

正如我们从官方文档中看到的,@Autowired 将构造函数、字段、setter 方法或配置方法标记为由 Spring 的依赖注入工具自动装配。 - https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Autowired.html

但是,spring 怎么知道你的方法是不是配置方法呢?当 Spring 找到 @Autowired 时,它将尝试查找与方法参数匹配的 bean 并调用该方法。

【讨论】:

    猜你喜欢
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多