Spring定义BeanDefinition

一、背景

注解( Annotation) 是 JDK1.5 中引入的 一个新特性。从Spring2.0以后的版本中,Spring引入了基于注解方式的配置 ,用于取代 XML 配置文件 ,从而极简化了 Bean 的配置,Spring后来的新版本。

话不多说,直接上图:

在Spring Boot 中完全采用基于注解 ( Spring4.x 引 入了更加智能的@Condition 系列注解,实现 “零 XML 的配置”(当然,同时也支持之前的 XML 配置文件方式)。

我们知道,@Component注解的功能是把普通 POJO实例化到 Spring容器中,相当于配置文件中的。

在类上添加注解@Configuration,表明这个类代表一个Spring配置文件,与原来 XML配置是等效的。只不过现在用 Java类加上一个@Configuration注解进行配置了,这种方式与XML 相比可以称得上是极简风格了。同时基于注解的配置风格,使得代码的可读性也大大增高了 。

二、AnnotationConfigApplicationContext

在开始分析之前,我们先运行一段简单的代码

@Configuration
public class MyConfig {

    @Bean
    public MyAnnoBean myAnnoBean(){
        return new MyAnnoBean();
    }
}

@Slf4j
public class AnnoMain {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext annoContext=new AnnotationConfigApplicationContext(MyConfig.class);
        Arrays.stream(annoContext.getBeanDefinitionNames()).forEach(log::info);
    }
}

输出结果如下:

14:04:41.566 [main] INFO org.example.springbean.AnnoMain - org.springframework.context.annotation.internalConfigurationAnnotationProcessor
14:04:41.566 [main] INFO org.example.springbean.AnnoMain - org.springframework.context.annotation.internalAutowiredAnnotationProcessor
14:04:41.566 [main] INFO org.example.springbean.AnnoMain - org.springframework.context.annotation.internalCommonAnnotationProcessor
14:04:41.566 [main] INFO org.example.springbean.AnnoMain - org.springframework.context.event.internalEventListenerProcessor
14:04:41.566 [main] INFO org.example.springbean.AnnoMain - org.springframework.context.event.internalEventListenerFactory
14:04:41.566 [main] INFO org.example.springbean.AnnoMain - myConfig
14:04:41.566 [main] INFO org.example.springbean.AnnoMain - myAnnoBea

我们发现除了myConfig,myAnnoBean两个我们自己想要加载的Bean之外,Spring在后台还给我们额外注入了5个Bean。我们暂且不用全部理解他们各自具有什么作用。我们先看一下相关代码。

/**
 * Register all relevant annotation post processors in the given registry. 
 * @param registry the registry to operate on
 * @param source the configuration source element (already extracted)
 * that this registration was triggered from. May be {@code null}.
 * @return a Set of BeanDefinitionHolders, containing all bean definitions
 * that have actually been registered by this call
 */
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
        BeanDefinitionRegistry registry, @Nullable Object source) {

    DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值