Why don't I need @Autowired in @Bean methods in the Spring configuration class?

Why does it 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!

+8
source share
3 answers

@Autowire allows you to inject beans from context into the "outside world" where the outside world is your application. Since you are in a "context of the world" with @Configuration classes, there is no need to explicitly autowire (look for a bean from the context).

Recall the analogy, for example, when accessing a method from a given instance. While you are in the instance scope, there is no need to write this to access the instance method, but the outside world will have to use the instance reference.

Edit

When you write the @Configuration class, you specify the metadata for the beans that the IOC will create.

@Autowire annotation, on the other hand, allows you to embed initialized beans, not metadata, into an application. Thus, there is no need for an explicit injection, because you are not working with beans when inside the Configuration class.

+12
source

Hello Jan Your question is marked as answered more than 4 years ago, but I found a better source: https://www.logicbig.com/tutorials/spring-framework/spring-core/javaconfig-methods-inter-dependency.html

here is another article with the same idea: https://dzone.com/articles/spring-configuration-and , it also says that such use is not well documented, which I consider to be true. (?)

in general, if the initialization of beanA depends on beanB , then Spring will bind them without explicit @Autowired annotation if you declare these two bean components in the application context (i.e. in the @Configuartion class).

enter image description here

0
source

A class with @Configuration annotation is where you define your beans for context. But the spring bean must define its own dependencies. Your four class B classes must define its own dependencies in the class definition. For example, if your class B depends on your class A, what it should look like this:

 public class B { @Autowired A aInstance; public A getA() { return aInstance; } public void setA(A a) { this.aInstance = a; } } 

In the above case, when spring creates its context, it searches for a bean that is of type A, which is also defined as a bean in your configuration class, and Autowires it to B at runtime so that B can use it if necessary.

-one
source

All Articles