为什么我在Spring配置类中不需要@Autowired @Bean方法? [英] Why do I not need @Autowired on @Bean methods in a Spring configuration class?

查看:900
本文介绍了为什么我在Spring配置类中不需要@Autowired @Bean方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样做:

@Configuration
public class MyConfig {

  @Bean
  public A getA() {
    return new A();
  }

  @Bean                 <-- Shouldn't I need @Autowired here?
  public B getB(A a) {
    return new B(a);
  }  
}

谢谢!

推荐答案

@Autowire 允许您将bean从上下文注入外部世界,其中外部世界是您的应用程序。
由于 @Configuration 类属于上下文世界,因此无需显式自动装配(从上下文中查找bean)。

@Autowire lets you inject beans from context to "outside world" where outside world is your application. Since with @Configuration classes you are within "context world ", there is no need to explicitly autowire (lookup bean from context).

想象一下从给定实例访问方法时的类比。当您在实例范围内时,无需编写来访问实例方法,但外部世界必须使用实例引用。

Think of analogy like when accessing method from a given instance. While you are within the instance scope there is no need to write this to access instance method, but outside world would have to use instance reference.

修改

当您编写 @Configuration 类时,您正在为将由IOC创建的bean指定元数据。

When you write @Configuration class, you are specifying meta data for beans which will be created by IOC.

@Autowire 注释让你注入初始化 bean,而不是meta -data,在应用程序中。因此,不需要显式注入,因为在 Configuration 类内部时,您不使用Beans。

@Autowire annotation on the other hand lets you inject initialized beans, not meta-data, in application. So, there is no need for explicit injection because you are not working with Beans when inside Configuration class.

这篇关于为什么我在Spring配置类中不需要@Autowired @Bean方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆