前言
上一篇文章提到过,@Bean注解往往和@Configuration配合,前者标注在方法上,后者标注在类上;两者搭配,将Bean注册到容器中。事实上,正如该注解字面上的意思一样,该注解不仅可以注册Bean,基本上配置相关的内容它都有涉及。
源码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
@AliasFor(
annotation = Component.class
)
String value() default "";
boolean proxyBeanMethods() default true;
}
我们可以从源码中可以看到,它实质上也是一个
@Component注解,所以该注解标记的类本身也会被注册成一个Bean
使用
它的使用方式我们在之前就提到过了
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
// instance, configure and return bean
}
}
它指示类生成一个或者多个@Bean方法,可以由Spring容器处理,在运行时为这些Bean生成BeanDefination和服务请求。