Spring使用手册

Spring使用手册

组件

组件注解 (@Component) + 组件扫描 (@ComponentScan)

@Import

为什么需要@Import(target)? 直接用@Bean new target不行吗? 换言之,target在什么情况下,只能用@Import而不能用@Bean?

答: 如果target是一个配置类,即它存在@ComponentScan、@Bean或@Import等等。使用@Bean时,这些配置将不会生效。

Q&A

Q: (在不同的地方) 多次@Import导入一个类,会有问题吗? 会产生什么影响?
A: 没有问题。但的确会产生一些影响,即合并importedBy。

ConfigurationClass existingClass = this.configurationClasses.get(configClass);
if (existingClass != null) {
    if (configClass.isImported()) {
       if (existingClass.isImported()) {
           // 合并importedBy
          existingClass.mergeImportedBy(configClass);
       }
       return;
    }
}

importedBy: 即target是被谁导入 (@Import) 的。

Tip: @EnableX 的本质其实是对@Import的应用。

说到底,使用@Import一般都是为了在app启动前,注册一些BeanDefinitions。

自动装配 (autowire) 集合

  • 自动装配的集合它的元素使有序的 (按order从小到大排序)。
  • Map的key必须是String

事件

  1. 定义新的事件类型 (继承ApplicationEvent)
  2. 声明对事件感兴趣的监听器 (实现ApplicationListener 或者 使用@EventListener注解)
  3. 在特定的时候,发布事件 (使用ApplicationEventPublisher)

异步

  1. 开启异步 (@EnableAsync)
  2. @Async

Condition

核心是@Conditional

@ConditionalOnProperty

示例:

@ConditionalOnProperty(prefix = "xyz", name = "x", havingValue = "wtf", matchIfMissing = true)

示例解释:

  • matchIfMissing = true: 如果没有设置xyz.x属性,则match true
  • prefix = "xyz", name = "x": 属性名为 xyz.x
  • havingValue = "wtf": 如果设置了xyz.x属性,且其属性值为"wtf",则match true; 否则match false
  • 总结: 设置了xyz.x属性,且属性值不为"wtf"时,match false; 否则match false

@ConditionalOnClass @ConditionalOnMissingClass

设计原则

  • 精确匹配优先
  • 操作幂等 + 信息合并
posted @ 2023-09-18 13:18  银桑V_V  阅读(34)  评论(0)    收藏  举报