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

前端 未结 3 1665
忘掉有多难
忘掉有多难 2020-12-24 15:22

Why does this work:

@Configuration
public class MyConfig {

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

  @Bean               // <-- Shouldn\'t I          


        
3条回答
  •  太阳男子
    2020-12-24 15:33

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

提交回复
热议问题