程序员必备的十大技能(进阶版)之精通主流框架与源码思想(二)

简介: 教程来源 http://qeext.cn/ 本文深入解析Spring框架中四大核心设计模式(工厂、模板方法、适配器、观察者)的实战应用,并详解Spring Boot自动配置原理:从@SpringBootApplication组合注解、spring.factories机制、条件化加载(@Conditional系列),到手写Starter实践,助你由源码理解走向约定优于配置的开发范式。

四、设计模式在框架中的实战

精通框架的另一个标志是能识别并理解框架中运用的设计模式。

4.1 工厂模式 —— BeanFactory

// BeanFactory是最顶层的工厂接口
public interface BeanFactory {
    Object getBean(String name) throws BeansException;
    <T> T getBean(Class<T> requiredType) throws BeansException;
}

4.2 模板方法模式 —— JdbcTemplate
JdbcTemplate将数据库操作的固定流程(获取连接、创建Statement、执行、处理结果、关闭资源)封装在模板方法中,而将变化的部分(SQL语句、结果集映射)留给回调实现:

// 简化版JdbcTemplate
public class JdbcTemplate {
    public <T> T query(String sql, RowMapper<T> rowMapper) {
        // 固定流程
        Connection conn = getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        // 变化部分交给回调
        T result = rowMapper.mapRow(rs);
        // 固定关闭
        close(rs, ps, conn);
        return result;
    }
}

4.3 适配器模式 —— HandlerAdapter
Spring MVC中,为什么@Controller、HttpRequestHandler、Servlet都可以作为处理器?因为HandlerAdapter做了适配:

public interface HandlerAdapter {
    boolean supports(Object handler);
    ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
}

// 针对不同Handler的实现
public class RequestMappingHandlerAdapter implements HandlerAdapter { ... }
public class SimpleControllerHandlerAdapter implements HandlerAdapter { ... }

4.4 观察者模式 —— ApplicationListener & ApplicationEvent
Spring的事件机制是观察者模式的典范:

// 自定义事件
public class OrderCreatedEvent extends ApplicationEvent {
    private final String orderId;
    public OrderCreatedEvent(Object source, String orderId) {
        super(source);
        this.orderId = orderId;
    }
}

// 监听器
@Component
public class OrderEventListener {
    @EventListener
    public void handleOrderCreated(OrderCreatedEvent event) {
        System.out.println("收到订单创建事件:" + event.getOrderId());
        // 发送短信、更新统计等
    }
}

// 发布事件
applicationContext.publishEvent(new OrderCreatedEvent(this, orderId));

底层原理:SimpleApplicationEventMulticaster遍历监听器列表,通过线程池异步或同步调用。

五、Spring Boot的自动配置 —— 走向约定的巅峰

Spring Boot通过“约定优于配置”极大降低了使用门槛,其灵魂在于@EnableAutoConfiguration。

5.1 @SpringBootApplication 组合注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootConfiguration
@EnableAutoConfiguration          // 核心!
@ComponentScan
public @interface SpringBootApplication {
}

5.2 @EnableAutoConfiguration 源码

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)  // 关键
public @interface EnableAutoConfiguration {
}

AutoConfigurationImportSelector的selectImports()方法会读取所有META-INF/spring.factories文件,获取org.springframework.boot.autoconfigure.EnableAutoConfiguration键对应的配置类列表。

5.3 spring.factories 示例(摘自spring-boot-autoconfigure)

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

5.4 条件注解体系
Spring Boot利用一系列@Conditional注解实现按需加载:

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RedisOperations.class)           // classpath中有RedisOperations才加载
@EnableConfigurationProperties(RedisProperties.class) // 绑定配置
public class RedisAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

常用条件注解:

@ConditionalOnClass / @ConditionalOnMissingClass

@ConditionalOnBean / @ConditionalOnMissingBean

@ConditionalOnProperty(如spring.redis.host是否存在)

@ConditionalOnWebApplication

5.5 手写一个简单的Starter
要理解自动配置,不妨自己实现一个Starter:

# pom.xml 命名规范:xxx-spring-boot-starter
// 配置属性类
@ConfigurationProperties(prefix = "sms")
public class SmsProperties {
    private String appId;
    private String secret;
    // getters/setters
}

// 服务类
public class SmsService {
    public void send(String phone, String content) {
        System.out.println("发送短信到 " + phone + ":" + content);
    }
}

// 自动配置类
@Configuration
@ConditionalOnClass(SmsService.class)
@EnableConfigurationProperties(SmsProperties.class)
public class SmsAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public SmsService smsService(SmsProperties properties) {
        SmsService service = new SmsService();
        // 可以初始化properties中的配置
        return service;
    }
}

// src/main/resources/META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.sms.SmsAutoConfiguration

其他项目引入这个Starter后,只需要配置sms.app-id和sms.secret,就可以@Autowired使用SmsService。
来源:
http://dffne.cn/

相关文章
|
缓存 Java API
【云原生】Spring Cloud Gateway的底层原理与实践方法探究
【云原生】Spring Cloud Gateway的底层原理与实践方法探究
|
7月前
|
程序员 API
初级程序员必备的十大技能之规范编码与团队协作(一)
教程来源 http://tmywi.cn/ 本文探讨程序员从“我能写”到“我们一起写”的成长跃迁,聚焦编码规范、代码审查、文档编写、协作沟通与工程化工具实践,助力个体迈向专业、可信赖的团队成员。
|
7月前
|
运维 Linux 程序员
初级程序员必备的十大技能之基础 Linux 命令(二)
教程来源 http://vrhyh.cn/ 本节系统介绍Linux文件内容查看与处理核心命令:`cat`快速显示/合并文件;`less`/`more`分页浏览;`head`/`tail`查看首尾及实时日志;`grep`精准搜索与过滤;`sed`流式文本替换删除;`awk`结构化字段处理;`vim`高效终端编辑。覆盖日常运维、日志分析与脚本开发必备技能。
|
7月前
|
SQL 存储 缓存
【Java基础】核心关键字:final、static、volatile、synchronized、transient(附《思维导图》+《面试高频考点清单》)
本文系统解析Java五大核心关键字:final(不可变性)、static(类级共享)、volatile(轻量级可见性)、synchronized(重量级同步)与transient(序列化控制)。涵盖语义、使用场景、底层原理(内存屏障、Monitor、类加载机制等)、常见误区及高频面试要点。
【Java基础】核心关键字:final、static、volatile、synchronized、transient(附《思维导图》+《面试高频考点清单》)
|
6月前
|
人工智能 Oracle 搜索推荐
2026年5 款 AI CRM 系统推荐
本文横评纷享销客、Salesforce、Dynamics 365、HubSpot、Oracle五款主流AI CRM,从技术底座(RAG/Agent/生态)、场景落地深度、行业适配性及安全合规等维度解析,破除“伪智能”陷阱,助力企业科学选型,聚焦真实提效与业务增长。
|
5月前
|
数据采集 存储 弹性计算
Playwright 无头爬虫部署阿里云 ECS 轻量服务器:解决浏览器内存溢出、IP 封禁、图片 OSS 存储完整方案
Bidfins日系中古藏品爬虫基于Playwright重构:通过阿里云ECS容器化部署、Redis动态代理池、OSS+CDN图片云存储,解决内存泄漏、IP封禁、磁盘溢出及并发阻塞四大痛点,单小时抓取量提升3倍,7天零中断,成本与性能显著优化。(239字)
713 0
|
6月前
|
存储 算法 C++
C++在高性能内存池(MemoryPool)设计与实现
频繁调用new/delete或malloc/free会造成性能损耗(系统调用、锁竞争、内存碎片)。
289 3
|
6月前
|
存储 程序员 调度
程序员必备的十大技能(进阶版)之底层计算机原理(一)
教程来源 http://zlpow.cn/ 本文深入计算机底层原理,涵盖体系结构、CPU微架构、内存层次、I/O、操作系统、汇编、编译链接等十大维度,揭示代码如何在硬件上高效运行,助开发者写出更可靠、高性能的程序。
|
7月前
|
存储 安全 Java
【Java基础】泛型:泛型擦除、通配符、上下界限定(附《思维导图》+《面试高频考点清单》)
本文系统梳理了Java泛型的核心知识体系,主要内容包括: 泛型概述:介绍了泛型的定义、本质和三大优势(类型安全、代码复用、可读性),以及泛型类、接口和方法的三种使用形式。 泛型擦除:深入解析了Java泛型实现的核心机制,包括擦除规则(无界类型擦除为Object,有界类型擦除为第一个边界类型)、擦除带来的问题(如无法使用instanceof、创建泛型数组等)及其解决方案。 泛型通配符:详细讲解了三种通配符类型(无界通配符、上界通配符和下界通配符)的语法、语义和使用场景。