Spring
June 6, 2020

M01 Q21 What does the @Bean annotation do?

@Bean annotation is used in @Configuration class to inform Spring that instance of class returned by method annotated with @Bean will return bean that will be managed by Spring.

@Bean also allows you to:

  • Specify the init method – will be called after an instance is created and assembled
  • Specify destroy method – will be called when a bean is discarded (usually when the context is getting closed)
  • Specify the name for the bean – by default bean has name autogenerated based on the method name, however, this can be overridden
  • Specify alias/aliases for the bean
  • Specify if Bean should be used as a candidate for injection into other beans – default true
  • Configure Autowiring mode – by name or type (Deprecated since Spring 5.1)