@Configuration
作用
声明当前类是一个配置类,相当于一个Spring的XML配置文件,与@Bean配合使用。
Instead of using the XML files, we can use plain Java classes to annotate the configurations by using the @Configuration annotation. If you annotate a class with @Configuration annotation, it indicates that the class is used for defining the beans using the @Bean annotation. This is very much similar to the element in the spring XML configurations.
@Configuration
public class JavaConfig {
@Bean(name="userDetails")
public UserDetails userDetails(){
return new UserDetails();
}
}
@Configuration VS @Component
- 共同点:都可以用于创建Bean;
- 不同点:实现原理不同,@Configuration基于CGlib代理实现,@Component基于反射实现;
- 使用场景:@Configuration用于全局配置,比如数据库相关配置,MVC相关配置等;业务Bean的配置使用注解配置(@Component,@Service,@Repository,@Controller)。
解析器注册时机
SpringApplication使用AnnotatedBeanDefinitionReader解析基于注解的Java配置,在AnnotatedBeanDefinitiaonReader构造方法中,AnnotationConfigUtils.registerAnnotationConfigProcessors(registry)为Java配置所使用到的注解添加后置处理器,其中有一个为ConfigurationClassPostProcessor
解析时机
AbstractApplicationContext的invokeBeanFactoryPostProcessors会触发调用BeanFactoryPostProcessor,ConfigurationClassPostProcessor作为@Configuration的解析器同样实现了BeanFactoryPostProcessor接口。
解析器处理逻辑
ConfigurationClassPostProcessor在postProcessBeanFactory中的主要逻辑是对配置类进行增强,如下所示:
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
增强逻辑
- 首先,将所有标注@Configuration的Bean筛选出来;
- 其次,对每个配置类使用CGlib进行增强;
- 对方法调用进行代理,防止嵌套调用时出现多个不同实例,具体可查看ConfigurationClassEnhancer;
参考:
推荐阅读
-
Opencv Configuration on MacOS
-
Spring3: Dependency Configuration In Detail(Part II) 博客分类: SpringFramework Spring 3.2.2IoCBeans.xmlConfigurationCollection
-
OLAP 玩转KYLIN 步十 官方案列实战之创建Cube之Configuration Overwrites
-
Spring注解驱动开发第2讲——使用@Configuration和@Bean给容器中注册组件
-
Spring Boot 踩坑之路之 Configuration Annotation Proessor not found in classpath 博客分类: springboot
-
Spring Boot 踩坑之路之 Configuration Annotation Proessor not found in classpath 博客分类: springboot
-
解决:No configuration found for the specified action 博客分类: struts2 StrutsJSPApacheXML工作
-
Spring(18)——使用Java类的形式配置bean 博客分类: Spring SpringJava@Configuration配置@Bean
-
【SpringBoot】Spring Boot Configuration Annotation Processor not found in classpath
-
spring boot Configuration Annotation Proessor not found in classpath