Annotation Interface Bean
Overview
The names and semantics of the attributes to this annotation are intentionally
similar to those of the <bean/>
element in the Spring XML schema. For
example:
@Bean public MyBean myBean() { // instantiate and configure MyBean obj return obj; }
Bean Names
While a name()
attribute is available, the default strategy for
determining the name of a bean is to use the name of the @Bean
method.
This is convenient and intuitive, but if explicit naming is desired, the
name
attribute (or its alias value
) may be used. Also note
that name
accepts an array of Strings, allowing for multiple names
(i.e. a primary bean name plus one or more aliases) for a single bean.
@Bean({"b1", "b2"}) // bean available as 'b1' and 'b2', but not 'myBean' public MyBean myBean() { // instantiate and configure MyBean obj return obj; }
Profile, Scope, Lazy, DependsOn, Primary, Order
Note that the @Bean
annotation does not provide attributes for profile,
scope, lazy, depends-on or primary. Rather, it should be used in conjunction with
@Scope
, @Lazy
, @DependsOn
and
@Primary
annotations to declare those semantics. For example:
@Bean @Profile("production") @Scope("prototype") public MyBean myBean() { // instantiate and configure MyBean obj return obj; }The semantics of the above-mentioned annotations match their use at the component class level:
@Profile
allows for selective inclusion of certain beans.
@Scope
changes the bean's scope from singleton to the specified scope.
@Lazy
only has an actual effect in case of the default singleton scope.
@DependsOn
enforces the creation of specific other beans before this
bean will be created, in addition to any dependencies that the bean expressed
through direct references, which is typically helpful for singleton startup.
@Primary
is a mechanism to resolve ambiguity at the injection point level
if a single target component needs to be injected but several beans match by type.
Additionally, @Bean
methods may also declare qualifier annotations
and @Order
values, to be
taken into account during injection point resolution just like corresponding
annotations on the corresponding component classes but potentially being very
individual per bean definition (in case of multiple definitions with the same
bean class). Qualifiers narrow the set of candidates after the initial type match;
order values determine the order of resolved elements in case of collection
injection points (with several target beans matching by type and qualifier).
NOTE: @Order
values may influence priorities at injection points,
but please be aware that they do not influence singleton startup order which is an
orthogonal concern determined by dependency relationships and @DependsOn
declarations as mentioned above. Also, Priority
is not
available at this level since it cannot be declared on methods; its semantics can
be modeled through @Order
values in combination with @Primary
on
a single bean per type.
@Bean
Methods in @Configuration
Classes
Typically, @Bean
methods are declared within @Configuration
classes. In this case, bean methods may reference other @Bean
methods in the
same class by calling them directly. This ensures that references between beans
are strongly typed and navigable. Such so-called 'inter-bean references' are
guaranteed to respect scoping and AOP semantics, just like getBean()
lookups
would. These are the semantics known from the original 'Spring JavaConfig' project
which require CGLIB subclassing of each such configuration class at runtime. As a
consequence, @Configuration
classes and their factory methods must not be
marked as final or private in this mode. For example:
@Configuration public class AppConfig { @Bean public FooService fooService() { return new FooService(fooRepository()); } @Bean public FooRepository fooRepository() { return new JdbcFooRepository(dataSource()); } // ... }
@Bean
Lite Mode
@Bean
methods may also be declared within classes that are not
annotated with @Configuration
. If a bean method is declared on a bean
that is not annotated with @Configuration
it is processed in a
so-called 'lite' mode.
Bean methods in lite mode will be treated as plain factory
methods by the container (similar to factory-method
declarations
in XML), with scoping and lifecycle callbacks properly applied. The containing
class remains unmodified in this case, and there are no unusual constraints for
the containing class or the factory methods.
In contrast to the semantics for bean methods in @Configuration
classes,
'inter-bean references' are not supported in lite mode. Instead,
when one @Bean
-method invokes another @Bean
-method in lite
mode, the invocation is a standard Java method invocation; Spring does not intercept
the invocation via a CGLIB proxy. This is analogous to inter-@Transactional
method calls where in proxy mode, Spring does not intercept the invocation —
Spring does so only in AspectJ mode.
For example:
@Component public class Calculator { public int sum(int a, int b) { return a+b; } @Bean public MyBean myBean() { return new MyBean(); } }
Bootstrapping
See the @Configuration
javadoc for further details including how to bootstrap
the container using AnnotationConfigApplicationContext
and friends.
BeanFactoryPostProcessor
-returning @Bean
methods
Special consideration must be taken for @Bean
methods that return Spring
BeanFactoryPostProcessor
(BFPP
) types. Because BFPP
objects must be instantiated very early in the
container lifecycle, they can interfere with processing of annotations such as @Autowired
,
@Value
, and @PostConstruct
within @Configuration
classes. To avoid these
lifecycle issues, mark BFPP
-returning @Bean
methods as static
. For example:
@Bean public static PropertySourcesPlaceholderConfigurer pspc() { // instantiate, configure and return pspc ... }By marking this method as
static
, it can be invoked without causing instantiation of its
declaring @Configuration
class, thus avoiding the above-mentioned lifecycle conflicts.
Note however that static
@Bean
methods will not be enhanced for scoping and AOP
semantics as mentioned above. This works out in BFPP
cases, as they are not typically
referenced by other @Bean
methods. As a reminder, an INFO-level log message will be
issued for any non-static @Bean
methods having a return type assignable to
BeanFactoryPostProcessor
.-
Nested Class Summary
Modifier and TypeClassDescriptionstatic enum
Local enumeration for the bootstrap mode. -
Optional Element Summary
Modifier and TypeOptional ElementDescriptionboolean
Is this bean a candidate for getting autowired into some other bean at all?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.boolean
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?The optional name of a method to call on the bean instance upon closing the application context, for example aclose()
method on a JDBCDataSource
implementation, or a HibernateSessionFactory
object.The optional name of a method to call on the bean instance during initialization.String[]
The name of this bean, or if several names, a primary bean name plus aliases.String[]
Alias forname()
.
-
Element Details
-
value
Alias forname()
.Intended to be used when no other attributes are needed, for example:
@Bean("customBeanName")
.- Since:
- 4.3.3
- See Also:
- Default:
- {}
-
name
The name of this bean, or if several names, a primary bean name plus aliases.If left unspecified, the name of the bean is the name of the annotated method. If specified, the method name is ignored.
The bean name and aliases may also be configured via the
value()
attribute if no other attributes are declared.- See Also:
- Default:
- {}
-
autowireCandidate
boolean autowireCandidateIs this bean a candidate for getting autowired into some other bean at all?Default is
true
; set this tofalse
for internal delegates that are not meant to get in the way of beans of the same type in other places.- Since:
- 5.1
- See Also:
- Default:
- true
-
defaultCandidate
boolean defaultCandidateIs 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?Default is
true
; set this tofalse
for restricted delegates that are supposed to be injectable in certain areas but are not meant to get in the way of beans of the same type in other places.This is a variation of
autowireCandidate()
which does not disable injection in general, just enforces an additional indication such as a qualifier.- Since:
- 6.2
- See Also:
- Default:
- true
-
bootstrap
Bean.Bootstrap bootstrapThe bootstrap mode for this bean: default is the main pre-instantiation thread for non-lazy singleton beans and the caller thread for prototype beans.Set
Bean.Bootstrap.BACKGROUND
to allow for instantiating this bean on a background thread. For a non-lazy singleton, a background pre-instantiation thread can be used then, while still enforcing the completion at the end ofConfigurableApplicationContext.refresh()
. For a lazy singleton, a background pre-instantiation thread can be used as well - with completion allowed at a later point, enforcing it when actually accessed.- Since:
- 6.2
- See Also:
- Default:
- DEFAULT
-
initMethod
String initMethodThe optional name of a method to call on the bean instance during initialization. Not commonly used, given that the method may be called programmatically directly within the body of a Bean-annotated method.The default value is
""
, indicating no init method to be called.- Default:
- ""
-
destroyMethod
String destroyMethodThe optional name of a method to call on the bean instance upon closing the application context, for example aclose()
method on a JDBCDataSource
implementation, or a HibernateSessionFactory
object. The method must have no arguments but may throw any exception.As a convenience to the user, the container will attempt to infer a destroy method against an object returned from the
@Bean
method. For example, given an@Bean
method returning an Apache Commons DBCPBasicDataSource
, the container will notice theclose()
method available on that object and automatically register it as thedestroyMethod
. This 'destroy method inference' is currently limited to detecting only public, no-arg methods named 'close' or 'shutdown'. The method may be declared at any level of the inheritance hierarchy and will be detected regardless of the return type of the@Bean
method (i.e., detection occurs reflectively against the bean instance itself at creation time).To disable destroy method inference for a particular
@Bean
, specify an empty string as the value, e.g.@Bean(destroyMethod="")
. Note that theDisposableBean
callback interface will nevertheless get detected and the corresponding destroy method invoked: In other words,destroyMethod=""
only affects custom close/shutdown methods andCloseable
/AutoCloseable
declared close methods.Note: Only invoked on beans whose lifecycle is under the full control of the factory, which is always the case for singletons but not guaranteed for any other scope.
- Default:
- "(inferred)"
-