The name of this bean, or if several names, a primary bean name plus aliases.
3
Is this bean a candidate for getting autowired into some other bean at all?
(Since 5.1)
4
Is this bean a candidate for getting autowired into some other bean based on the plain type, without any further indications such as a qualifier match?
(Since 6.2)
5
The bootstrap mode for this bean: default is the main pre-instantiation thread for non-lazy singleton beans and the caller thread for prototype beans.
(Since 6.2)
6
The optional name of a method to call on the bean instance during initialization.
7
The optional name of a method to call on the bean instance upon closing the application context, for example a close() method on a JDBC DataSource implementation, or a Hibernate SessionFactory object.
8
Local enumeration for the bootstrap mode.
(Since 6.2)
9
Constant to indicate the main pre-instantiation thread for non-lazy singleton beans and the caller thread for prototype beans.
10
Allow for instantiating a bean on a background thread.
The @Bean annotation is used on Java based configuration method. Following quick examples show basic usages:
name :
The optional bean name.
@Configuration
public class AppConfig {
@Bean(name = "myBean")
public MyBean createBean() {
......
}
}
By default Spring container associate the bean with method name .
A bean can be associated with multiple names, the extra ones are considered aliases.
Specifying a unique meaningful name to a bean is necessary if the configuration provides more than one implementations for a bean. In that case, we have to use @Qualifier at the injection point which has an option to specify the bean name. An example here.
initMethod/destroyMethod :
Optional initialization and destruction callback method names.
@Configuration
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "destroy")
public MyBean createBean() {
......
}
}
The destroy method will only be called for singletons but not for other scoped as Spring does not manage complete life cycle of the other beans.
In case of singleton this method is called upon closing the application context.
Since Spring also supports Java SE Common Annotations (JSR-250), we can annotate bean's methods with @PostConstruct and @PreDestroy instead of these elements. Please see an example here.
There's one more annotation from JSR-250 that Spring supports, @Resource. Please see an example here.