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

简介: 教程来源 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/

相关文章
|
2月前
|
算法 安全 测试技术
多智能体协同中的任务拆解与动作映射:关键指标对比与算法设计思路
本文聚焦2026年企业级多智能体落地核心瓶颈——任务拆解不准与语义到动作映射断层,提出“分层级树状拆解+分布式角色调度”算法及五维特征驱动的动作映射技术,构建可评估、可复用、强合规的工程化方案,并通过实测数据验证其在跨系统长链路任务中96.2%执行成功率与92.3%异常自修复率。
|
2月前
|
机器学习/深度学习 前端开发 算法
SBTI的爆火
SBTI是MBTI的戏谑变体,借熟为人知的认知框架,用网络热梗命名(如“吗喽”“酒鬼”)替代严肃人格标签。纯前端实现、零后端依赖,结果稳定易传播。它不追求心理科学性,而是精准击中当代青年自嘲、情绪化表达需求,成为社交平台的现象级“状态名片”。以上服务部署全部托管oss
892 6
|
7天前
|
人工智能 Oracle 搜索推荐
2026年5 款 AI CRM 系统推荐
本文横评纷享销客、Salesforce、Dynamics 365、HubSpot、Oracle五款主流AI CRM,从技术底座(RAG/Agent/生态)、场景落地深度、行业适配性及安全合规等维度解析,破除“伪智能”陷阱,助力企业科学选型,聚焦真实提效与业务增长。
|
7天前
|
存储 程序员 调度
程序员必备的十大技能(进阶版)之底层计算机原理(一)
教程来源 http://zlpow.cn/ 本文深入计算机底层原理,涵盖体系结构、CPU微架构、内存层次、I/O、操作系统、汇编、编译链接等十大维度,揭示代码如何在硬件上高效运行,助开发者写出更可靠、高性能的程序。
|
30天前
|
程序员 API
初级程序员必备的十大技能之规范编码与团队协作(一)
教程来源 http://tmywi.cn/ 本文探讨程序员从“我能写”到“我们一起写”的成长跃迁,聚焦编码规范、代码审查、文档编写、协作沟通与工程化工具实践,助力个体迈向专业、可信赖的团队成员。
|
30天前
|
程序员 开发工具 git
初级程序员必备的十大技能之规范编码与团队协作(三)
教程来源 http://qcycj.cn/ 本节系统阐述高效团队协作核心实践:从精准提问、高效会议、知识共享到冲突化解,并配套自动化工具链(Prettier/ESLint/Husky/Commitlint/GitHub Actions),全面提升研发协同质量与工程规范性。
|
7天前
|
缓存 API PHP
PHP在GraphQLAPI实现中的应用(以Lighthouse为例)
相比REST,GraphQL允许客户端精确指定所需字段,减少过度获取;单个端点支持复杂查询;强类型schema。
72 5
|
2月前
|
SQL 数据采集 自然语言处理
怎么判断数据智能平台的用户体验是否真的能让业务人员愿意用?
本文聚焦企业智能问数平台“业务人员愿不愿用”的本质——非界面体验,而是**可持续信任**:答得准、复杂场景稳、错误可识别、上线后准确率可持续。强调准确率评估须分五维(结果/口径/语义稳健/复杂问题/可解释),并区分开卷与闭卷测试。截至2026年4月,成熟度高度分层,关键在匹配场景与治理能力。
|
30天前
|
运维 监控 Linux
初级程序员必备的十大技能之基础 Linux 命令(五)
教程来源 http://xgmoi.cn/ 本节汇总Linux系统监控与管理核心命令:磁盘(df/du)、内存(free)、运行状态(uptime/ uname)、打包压缩(tar/zip)、用户权限、日志查看及速查表,覆盖运维日常高频操作,简洁实用。

热门文章

最新文章