Why do I not need @Autowired on @Bean methods in a Spring configuration class?

假如想象 提交于 2019-12-18 11:57:47

问题


Why does this work:

@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);
  }  
}

Thanks!


回答1:


@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.

Edit

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

@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.




回答2:


Hi Jan your question is marked as answered over 4 years ago but I've found a better source: https://www.logicbig.com/tutorials/spring-framework/spring-core/javaconfig-methods-inter-dependency.html

here's another article with the same idea: https://dzone.com/articles/spring-configuration-and, it also states that such usage is not well documented which I found true. (?)

so basically if beanA's initialization depends on beanB, spring will wire them without explicit @Autowired annotation as long as you declare these two beans in the application context (i.e. @Configuartion class).




回答3:


A class with @Configuration annotation is where you're defining your beans for the context. But a spring bean should define its own dependencies. Four your case B class should be defining it's own dependencies in class definition. For example if your B class depends on your A class than it should be like below:

public class B
{
    @Autowired
    A aInstance;

    public A getA()
    {
        return aInstance;
    }

    public void setA(A a)
    {
        this.aInstance =  a;
    }
}

In above case while spring is building its context it looks for the bean which's type is A which is also defined as a Bean at your configuration class and Autowires it to B at runtime so that B can use it when required.



来源:https://stackoverflow.com/questions/32078600/why-do-i-not-need-autowired-on-bean-methods-in-a-spring-configuration-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!