001/*
002 * Copyright 2002-2017 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.context.annotation;
018
019import java.lang.annotation.Documented;
020import java.lang.annotation.ElementType;
021import java.lang.annotation.Retention;
022import java.lang.annotation.RetentionPolicy;
023import java.lang.annotation.Target;
024
025import org.springframework.beans.factory.annotation.Autowire;
026import org.springframework.beans.factory.support.AbstractBeanDefinition;
027import org.springframework.core.annotation.AliasFor;
028
029/**
030 * Indicates that a method produces a bean to be managed by the Spring container.
031 *
032 * <h3>Overview</h3>
033 *
034 * <p>The names and semantics of the attributes to this annotation are intentionally
035 * similar to those of the {@code <bean/>} element in the Spring XML schema. For
036 * example:
037 *
038 * <pre class="code">
039 *     &#064;Bean
040 *     public MyBean myBean() {
041 *         // instantiate and configure MyBean obj
042 *         return obj;
043 *     }
044 * </pre>
045 *
046 * <h3>Bean Names</h3>
047 *
048 * <p>While a {@link #name} attribute is available, the default strategy for
049 * determining the name of a bean is to use the name of the {@code @Bean} method.
050 * This is convenient and intuitive, but if explicit naming is desired, the
051 * {@code name} attribute (or its alias {@code value}) may be used. Also note
052 * that {@code name} accepts an array of Strings, allowing for multiple names
053 * (i.e. a primary bean name plus one or more aliases) for a single bean.
054 *
055 * <pre class="code">
056 *     &#064;Bean({"b1", "b2"}) // bean available as 'b1' and 'b2', but not 'myBean'
057 *     public MyBean myBean() {
058 *         // instantiate and configure MyBean obj
059 *         return obj;
060 *     }
061 * </pre>
062 *
063 * <h3>Profile, Scope, Lazy, DependsOn, Primary, Order</h3>
064 *
065 * <p>Note that the {@code @Bean} annotation does not provide attributes for profile,
066 * scope, lazy, depends-on or primary. Rather, it should be used in conjunction with
067 * {@link Scope @Scope}, {@link Lazy @Lazy}, {@link DependsOn @DependsOn} and
068 * {@link Primary @Primary} annotations to declare those semantics. For example:
069 *
070 * <pre class="code">
071 *     &#064;Bean
072 *     &#064;Profile("production")
073 *     &#064;Scope("prototype")
074 *     public MyBean myBean() {
075 *         // instantiate and configure MyBean obj
076 *         return obj;
077 *     }
078 * </pre>
079 *
080 * The semantics of the above-mentioned annotations match their use at the component
081 * class level: {@code Profile} allows for selective inclusion of certain beans.
082 * {@code @Scope} changes the bean's scope from singleton to the specified scope.
083 * {@code @Lazy} only has an actual effect in case of the default singleton scope.
084 * {@code @DependsOn} enforces the creation of specific other beans before this
085 * bean will be created, in addition to any dependencies that the bean expressed
086 * through direct references, which is typically helpful for singleton startup.
087 * {@code @Primary} is a mechanism to resolve ambiguity at the injection point level
088 * if a single target component needs to be injected but several beans match by type.
089 *
090 * <p>Additionally, {@code @Bean} methods may also declare qualifier annotations
091 * and {@link org.springframework.core.annotation.Order @Order} values, to be
092 * taken into account during injection point resolution just like corresponding
093 * annotations on the corresponding component classes but potentially being very
094 * individual per bean definition (in case of multiple definitions with the same
095 * bean class). Qualifiers narrow the set of candidates after the initial type match;
096 * order values determine the order of resolved elements in case of collection
097 * injection points (with several target beans matching by type and qualifier).
098 *
099 * <p><b>NOTE:</b> {@code @Order} values may influence priorities at injection points
100 * but please be aware that they do not influence singleton startup order which is an
101 * orthogonal concern determined by dependency relationships and {@code @DependsOn}
102 * declarations as mentioned above. Also, {@link javax.annotation.Priority} is not
103 * available at this level since it cannot be declared on methods; its semantics can
104 * be modelled through {@code @Order} values in combination with {@code @Primary} on
105 * a single bean per type.
106 *
107 * <h3>{@code @Bean} Methods in {@code @Configuration} Classes</h3>
108 *
109 * <p>Typically, {@code @Bean} methods are declared within {@code @Configuration}
110 * classes. In this case, bean methods may reference other {@code @Bean} methods in the
111 * same class by calling them <i>directly</i>. This ensures that references between beans
112 * are strongly typed and navigable. Such so-called <em>'inter-bean references'</em> are
113 * guaranteed to respect scoping and AOP semantics, just like {@code getBean()} lookups
114 * would. These are the semantics known from the original 'Spring JavaConfig' project
115 * which require CGLIB subclassing of each such configuration class at runtime. As a
116 * consequence, {@code @Configuration} classes and their factory methods must not be
117 * marked as final or private in this mode. For example:
118 *
119 * <pre class="code">
120 * &#064;Configuration
121 * public class AppConfig {
122 *
123 *     &#064;Bean
124 *     public FooService fooService() {
125 *         return new FooService(fooRepository());
126 *     }
127 *
128 *     &#064;Bean
129 *     public FooRepository fooRepository() {
130 *         return new JdbcFooRepository(dataSource());
131 *     }
132 *
133 *     // ...
134 * }</pre>
135 *
136 * <h3>{@code @Bean} <em>Lite</em> Mode</h3>
137 *
138 * <p>{@code @Bean} methods may also be declared within classes that are <em>not</em>
139 * annotated with {@code @Configuration}. For example, bean methods may be declared
140 * in a {@code @Component} class or even in a <em>plain old class</em>. In such cases,
141 * a {@code @Bean} method will get processed in a so-called <em>'lite'</em> mode.
142 *
143 * <p>Bean methods in <em>lite</em> mode will be treated as plain <em>factory
144 * methods</em> by the container (similar to {@code factory-method} declarations
145 * in XML), with scoping and lifecycle callbacks properly applied. The containing
146 * class remains unmodified in this case, and there are no unusual constraints for
147 * the containing class or the factory methods.
148 *
149 * <p>In contrast to the semantics for bean methods in {@code @Configuration} classes,
150 * <em>'inter-bean references'</em> are not supported in <em>lite</em> mode. Instead,
151 * when one {@code @Bean}-method invokes another {@code @Bean}-method in <em>lite</em>
152 * mode, the invocation is a standard Java method invocation; Spring does not intercept
153 * the invocation via a CGLIB proxy. This is analogous to inter-{@code @Transactional}
154 * method calls where in proxy mode, Spring does not intercept the invocation &mdash;
155 * Spring does so only in AspectJ mode.
156 *
157 * <p>For example:
158 *
159 * <pre class="code">
160 * &#064;Component
161 * public class Calculator {
162 *     public int sum(int a, int b) {
163 *         return a+b;
164 *     }
165 *
166 *     &#064;Bean
167 *     public MyBean myBean() {
168 *         return new MyBean();
169 *     }
170 * }</pre>
171 *
172 * <h3>Bootstrapping</h3>
173 *
174 * <p>See the @{@link Configuration} javadoc for further details including how to bootstrap
175 * the container using {@link AnnotationConfigApplicationContext} and friends.
176 *
177 * <h3>{@code BeanFactoryPostProcessor}-returning {@code @Bean} methods</h3>
178 *
179 * <p>Special consideration must be taken for {@code @Bean} methods that return Spring
180 * {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessor}
181 * ({@code BFPP}) types. Because {@code BFPP} objects must be instantiated very early in the
182 * container lifecycle, they can interfere with processing of annotations such as {@code @Autowired},
183 * {@code @Value}, and {@code @PostConstruct} within {@code @Configuration} classes. To avoid these
184 * lifecycle issues, mark {@code BFPP}-returning {@code @Bean} methods as {@code static}. For example:
185 *
186 * <pre class="code">
187 *     &#064;Bean
188 *     public static PropertySourcesPlaceholderConfigurer pspc() {
189 *         // instantiate, configure and return pspc ...
190 *     }
191 * </pre>
192 *
193 * By marking this method as {@code static}, it can be invoked without causing instantiation of its
194 * declaring {@code @Configuration} class, thus avoiding the above-mentioned lifecycle conflicts.
195 * Note however that {@code static} {@code @Bean} methods will not be enhanced for scoping and AOP
196 * semantics as mentioned above. This works out in {@code BFPP} cases, as they are not typically
197 * referenced by other {@code @Bean} methods. As a reminder, a WARN-level log message will be
198 * issued for any non-static {@code @Bean} methods having a return type assignable to
199 * {@code BeanFactoryPostProcessor}.
200 *
201 * @author Rod Johnson
202 * @author Costin Leau
203 * @author Chris Beams
204 * @author Juergen Hoeller
205 * @author Sam Brannen
206 * @since 3.0
207 * @see Configuration
208 * @see Scope
209 * @see DependsOn
210 * @see Lazy
211 * @see Primary
212 * @see org.springframework.stereotype.Component
213 * @see org.springframework.beans.factory.annotation.Autowired
214 * @see org.springframework.beans.factory.annotation.Value
215 */
216@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
217@Retention(RetentionPolicy.RUNTIME)
218@Documented
219public @interface Bean {
220
221        /**
222         * Alias for {@link #name}.
223         * <p>Intended to be used when no other attributes are needed, for example:
224         * {@code @Bean("customBeanName")}.
225         * @since 4.3.3
226         * @see #name
227         */
228        @AliasFor("name")
229        String[] value() default {};
230
231        /**
232         * The name of this bean, or if several names, a primary bean name plus aliases.
233         * <p>If left unspecified, the name of the bean is the name of the annotated method.
234         * If specified, the method name is ignored.
235         * <p>The bean name and aliases may also be configured via the {@link #value}
236         * attribute if no other attributes are declared.
237         * @see #value
238         */
239        @AliasFor("value")
240        String[] name() default {};
241
242        /**
243         * Are dependencies to be injected via convention-based autowiring by name or type?
244         * <p>Note that this autowire mode is just about externally driven autowiring based
245         * on bean property setter methods by convention, analogous to XML bean definitions.
246         * <p>The default mode does allow for annotation-driven autowiring. "no" refers to
247         * externally driven autowiring only, not affecting any autowiring demands that the
248         * bean class itself expresses through annotations.
249         * @see Autowire#BY_NAME
250         * @see Autowire#BY_TYPE
251         */
252        Autowire autowire() default Autowire.NO;
253
254        /**
255         * The optional name of a method to call on the bean instance during initialization.
256         * Not commonly used, given that the method may be called programmatically directly
257         * within the body of a Bean-annotated method.
258         * <p>The default value is {@code ""}, indicating no init method to be called.
259         * @see org.springframework.beans.factory.InitializingBean
260         * @see org.springframework.context.ConfigurableApplicationContext#refresh()
261         */
262        String initMethod() default "";
263
264        /**
265         * The optional name of a method to call on the bean instance upon closing the
266         * application context, for example a {@code close()} method on a JDBC
267         * {@code DataSource} implementation, or a Hibernate {@code SessionFactory} object.
268         * The method must have no arguments but may throw any exception.
269         * <p>As a convenience to the user, the container will attempt to infer a destroy
270         * method against an object returned from the {@code @Bean} method. For example, given
271         * an {@code @Bean} method returning an Apache Commons DBCP {@code BasicDataSource},
272         * the container will notice the {@code close()} method available on that object and
273         * automatically register it as the {@code destroyMethod}. This 'destroy method
274         * inference' is currently limited to detecting only public, no-arg methods named
275         * 'close' or 'shutdown'. The method may be declared at any level of the inheritance
276         * hierarchy and will be detected regardless of the return type of the {@code @Bean}
277         * method (i.e., detection occurs reflectively against the bean instance itself at
278         * creation time).
279         * <p>To disable destroy method inference for a particular {@code @Bean}, specify an
280         * empty string as the value, e.g. {@code @Bean(destroyMethod="")}. Note that the
281         * {@link org.springframework.beans.factory.DisposableBean} callback interface will
282         * nevertheless get detected and the corresponding destroy method invoked: In other
283         * words, {@code destroyMethod=""} only affects custom close/shutdown methods and
284         * {@link java.io.Closeable}/{@link java.lang.AutoCloseable} declared close methods.
285         * <p>Note: Only invoked on beans whose lifecycle is under the full control of the
286         * factory, which is always the case for singletons but not guaranteed for any
287         * other scope.
288         * @see org.springframework.beans.factory.DisposableBean
289         * @see org.springframework.context.ConfigurableApplicationContext#close()
290         */
291        String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;
292
293}