1

What is the difference between @Bean and @Autowired in Spring?

As far as I understood we can use both to inject dependencies, @Autowired when the interface was implemented just in one class, and @Bean, when the interface was implemented in more than one class, in the last case @configuration, is required.

thanks in advance

Luis Montano
  • 51
  • 1
  • 6

4 Answers4

7

In short @Bean is producer and @Autowired is consumer, @Bean annotation let spring know instance of this class and it hold for it and @Autowired annotation ask for please give me instance of class which we created with @Bean annotation.

more detailed answer find here

4

When you use @Bean you are telling to Spring that:

this is the object that I want you to put within your stack and later I will ask about it from you

And When you use @Autowired you are telling to Spring that:

Now please give me the object that I already told you to keep it in your stack (means the @Bean object)

Mehdi
  • 3,795
  • 3
  • 36
  • 65
2

When you use @Bean you are responsible for providing an Id and calling that Id when you wish to use that particular object using getBean() method. Autowired helps avoid the calling part and returns an object everytime it is needed. Spring handles the job of returning the appropriate object and helps reduce additional syntax for referring to a particular bean.

2

Spring provides a very nice documentation about Autowired and Bean API

@BEAN

@Target(value={METHOD,ANNOTATION_TYPE})
@Retention(value=RUNTIME)
@Documented
public @interface Bean

Indicates that a method produces a bean to be managed by the Spring container.

On Bean @Target annotation confirms that it can be applied over a METHOD.

@AUTOWIRED

@Target(value={CONSTRUCTOR,METHOD,PARAMETER,FIELD,ANNOTATION_TYPE})
@Retention(value=RUNTIME)
@Documented
public @interface Autowired

Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities. This is an alternative to the JSR-330 Inject annotation.

On Autowired @Target confirms that it can be applied over a CONSTRUCTOR,METHOD,PARAMETER,FIELD.

IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean.

Gaurav Pathak
  • 2,576
  • 1
  • 10
  • 20