Spring Boot自动装配原理

Spring Boot 中自动装配机制的原理 可能用户还会问到如何自定义自动配置,比如编写自己的starter,这时候需要创建spring.factories文件,定义自己的AutoConfiguration类,并使用条件注解来控制Bean的创建。这也是Spring Boot扩展性的一种体现。 总结一下,我需要分步骤解释自动装配的机制,从@EnableAutoConfiguration开始,到加载spring.factories中的配置类,条件注解的作用,以及整个装配流程。同时要对比组件扫描和自动装配的不同,避免用户混淆。可能还需要提到一些常见的自动 阅读详情

一、核心入口:@SpringBootApplication 注解

Spring Boot 应用的主类通常会添加 @SpringBootApplication 注解,它是一个组合注解,主要包含以下三个关键注解:

  • @SpringBootConfiguration:继承自 @Configuration,表明该类是一个配置类,可用于定义 Bean 等配置信息。
  • @EnableAutoConfiguration:此注解是开启自动装配功能的核心,它借助 @Import 导入了 AutoConfigurationImportSelector 类,为后续自动装配流程奠定基础。
  • @ComponentScan:负责扫描指定包及其子包下带有 @Component、@Service、@Repository、@Controller 等注解的组件,并将它们注册到 Spring 容器中。

二、自动配置类的加载:AutoConfigurationImportSelector 类

@EnableAutoConfiguration 注解导入的 AutoConfigurationImportSelector 类发挥着重要作用,其核心功能如下:

  • 读取 spring.factories 文件:该类会从 META - INF/spring.factories 文件中读取自动配置类的全限定名。众多 Spring Boot 依赖模块都可在自身的 spring.factories 文件中定义自动配置类。例如,spring - boot - starter - web 依赖会定义与 Web 开发相关的自动配置类,像 WebMvcAutoConfiguration 等。
  • spring.factories 文件格式:这是一个 properties 格式的文件,以 org.springframework.boot.autoconfigure.EnableAutoConfiguration 作为键,值为逗号分隔的自动配置类全限定名列表。示例如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

三、条件筛选:@Conditional 注解及其派生注解

为了确保自动配置类在合适的条件下生效,Spring Boot 自动配置类上广泛使用了各种 @Conditional 注解的派生注解,常见的有:

  • @ConditionalOnClass:当类路径中存在指定的类时,对应的自动配置类才会被应用。例如,WebMvcAutoConfiguration 类上标注了 @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class }),意味着只有当类路径中同时存在 Servlet、DispatcherServlet 和 WebMvcConfigurer 类时,该自动配置类才会生效。
  • @ConditionalOnMissingBean:若 Spring 容器中不存在指定类型的 Bean,相应的自动配置类才会被应用。比如在数据源的自动配置类中,会检查容器中是否已存在 DataSource 类型的 Bean,若不存在则进行自动配置。
  • @ConditionalOnProperty:当指定的属性存在且满足特定条件时,自动配置类才会生效。例如,@ConditionalOnProperty(name = "spring.cache.type", havingValue = "redis") 表示只有当配置文件中存在 spring.cache.type 属性且其值为 redis 时,相关的 Redis 缓存自动配置类才会生效。

四、自动配置类的作用

自动配置类的主要职责是通过 @Bean 注解定义方法,将一些常用的组件(如 DataSource、JdbcTemplate、RestTemplate 等)配置到 Spring 容器中。开发者可根据自身需求,对这些自动配置的 Bean 进行覆盖或自定义配置。例如,DataSourceAutoConfiguration 类会依据不同的数据库连接池依赖(如 HikariCP、Tomcat JDBC 等),自动配置 DataSource Bean 并注册到 Spring 容器中,供其他组件使用。

五、总结

Spring Boot 的自动装配原理是通过 @EnableAutoConfiguration 注解触发从 spring.factories 文件加载自动配置类,再利用各种条件注解决定自动配置类是否生效,最终将常用组件配置到 Spring 容器中,从而实现应用的快速搭建和自动配置。

Spring Boot源码解析 - 自动装配原理 作为自动装配核心类,在处理@Import逻辑中触发自动装配的过程,最终获取需要导入的自动装配类集合,实现Spring Boot的自动装配功能。注解,我们可以在一个配置类中引入其他的配置类,从而将它们的Bean定义和配置合并到当前配置中。,以key-value的形式进行本地缓存,后续触发自动装配时,从本地缓存中获取自动装配类集合。后置处理器会在扫描解析启动类当前包以及子包下的配置类,并将其注册为Spring管理的。,其他部分与自动装配无关。的自动装配类集合,然后去重过滤返回需要导入的自动装配类数组。 阅读详情

相关推荐

Spring Boot 的自动装配原理

ComponentScan: 扫描包下的类中添加了@Component (@Service,@Controller,@Repostory,@RestController)注解的类 ,并添加的到spring的容器中,可以自定义不扫描某些 bean。Dubbo的SPI机制:Dubbo更是把SPI机制应用的淋漓尽致,Dubbo基本上自身的每个功能点都提供了扩展点,比如提供了集群扩展,路由扩展和负载均衡扩展等差不多接近30个扩展点。Spring Boot 只是在其基础上,通过 SPI 的方式,做了进一步优化。

qq_38667268的博客 425

Spring Boot 自动装配原理详解

自动装配是 Spring Boot 根据项目类路径(classpath)中的依赖和当前环境,动态配置 Spring 应用程序所需 Bean 的过程。它通过注解实现,通常被包含在中。核心功能:根据引入的依赖,自动加载和配置相关组件。典型场景:添加后,Spring Boot 自动配置 Tomcat 和 Spring MVC。// 文件: org.springframework.boot.autoconfigure.EnableAutoConfiguration。

error_log7的博客 2647

Edge主页被2345劫持?手动清理注册表与组策略的完整方案

浏览器主页劫持是Windows系统中常见的恶意篡改行为,其原理是通过修改注册表、快捷方式、组策略等多处系统配置,强制锁定浏览器启动页。这类劫持不仅影响上网体验,还可能带来隐私泄露和恶意软件感染风险。在安全防护与系统优化场景中,掌握手动清理主页劫持的技能至关重要。本文针对Edge主页被2345导航劫持的问题,深入解析劫持入口,提供从快捷方式、注册表到组策略的逐层清理步骤,并给出防复发策略,帮助用户彻底摆脱顽固劫持。

weixin_30582943的博客 388

spring boot自动装配原理

springboot自动装配几乎是现在面试必问的面试题,要是逐行分析自动装配流程肯定是很复杂的,因此我们从大体上来梳理即可。

u012453843的专栏 1383

从Live2D到Unreal Engine:2D与3D虚拟数字人核心技术实现路径解析

本文深入解析了从Live2D到Unreal Engine的2D与3D虚拟数字人核心技术实现路径,涵盖技术选型、制作流程与优化技巧。通过对比2D骨骼动画与3D建模渲染的差异,结合实战案例,帮助开发者根据项目需求选择合适方案,提升虚拟数字人的交互体验与视觉效果。

weixin_30379531的博客 149

<硬件设计> 阻抗设计(二) 使用Si9000计算阻抗

阻抗设计(二) 使用Si9000计算阻抗

杰克拉力船长个人博客 1万+

最近一场面试(Spring Boot的自动装配原理及流程)

一、前言 面试官:“可不可以说一下Spring Boot的自动装配原理?” 我:“不可以。” 面试官:“滚出去!!!” 二、回顾在普通的Spring项目中的做法 在没有使用Spring Boot之前,我们需要在xml文件中进行需要用到的Bean的配置(以最常用的mybatis的使用为例)。 在使用到mybatis时,我们需要配置相关的Bean(DataSource的bean、SqlSessionFactory的bean) 而在用到Spring Boot后,我们只需要引入依赖,再加上.

心有谦谦结 1万+

CANoe LIN一致性测试之干扰测试Test moudle_LIN Disturbance Block

注意:相邻两个显隐性不同的bit不允许干扰,例如我同时选择bit6和bit7,相邻两个同显隐性的bit允许干扰,例如当我选择bit3和bit4,项,这里我选择ID:为0x2F(PID:0x6F)的frame。需按照具体测试规范实施干扰项,帧头和数据段都可以实现干扰。最近发现一个干扰测试模块,下面是一些具体使用方法。选择干扰项:PID的奇偶校验位(一致性测试干扰测试之手动测试。一个待测试frameD。

yuanyikangkang的博客 3412

Spring boot 自动装配原理

Spring boot 自动装配原理

Java是世界上最好的语言 1481

三款云电脑实测:ToDesk、青椒云、顺网云谁更适合AIGC新手?附详细配置对比

本文针对AIGC新手,深度实测了ToDesk云电脑、青椒云和顺网云三款云电脑服务。通过对比上手门槛、内置生态、操作引导及成本,发现ToDesk云电脑凭借一键启动、丰富预置模型和直观引导,为新手提供了最接近“开箱即用”的零门槛AIGC创作体验,是快速入门AI绘画的高效选择。

assembly8low的博客 1095

AD快速上手笔记

本文详细介绍了使用Altium Designer从零创建PCB项目全流程:新建工程、绘制原理图(元件放置、连线、电源端口)、编译检查、生成PCB、布局布线(含铺铜)、DRC检查及输出Gerber与钻孔文件。重点强调了库选择、参数修改、层切换、铺铜设置和生产文件导出规范,确保设计无误,便于顺利下单生产。

qq_53529450的博客 42

Spring Boot 自动装配原理

Spring Boot自动装配原理基于约定优于配置的设计思想,通过@EnableAutoConfiguration注解触发自动配置流程。开发者可创建自定义starter,通过定义配置类和spring.factories实现扩展。整个过程体现了Spring Boot"开箱即用"的特性,大幅简化了传统Spring应用的配置工作。

无论云泥意贯一 1286

FT2004(D2000)开发实战之AMD R5 230显卡驱动适配

AMD R5 230显卡驱动适配

嵌入式Linux 3200

Spring Boot自动装配原理深度解析

约定优于配置:通过默认配置减少显式配置条件化装配:根据classpath内容、环境变量等条件决定是否启用配置模块化配置:每个starter模块提供自己的默认配置当开发者添加某个starter依赖(如)时,Spring Boot会自动配置所需的Bean,而无需手动编写配置类。新建Maven项目,添加依赖:</</</创建自动配置类:@Bean添加配置属性类:创建spring.factories:在应用项目中添加依赖:</</</</

Gaomengsuanjia_的博客 953

Python实战项目2:b站评论采集

本文不对数据采集的过程做探讨,直接上代码。

lyccomcn的博客 3200

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

Spring Boot 自动装配的原理

Spring Boot自动装配1. 自动装配的原理1.1自动装配的实现1.1.1@EnableAutoConfiguration1.1.2

weixin_40718971的博客 750

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring Boot Starter 自动装配原理全解析:从概念到实践

在Spring Boot开发中,**Starter**和**自动装配**是两个核心概念,它们共同构成了“开箱即用”的开发体验。通过引入一个`Starter`依赖,开发者可以快速集成第三方组件(如Redis、MyBatis等),而无需手动配置大量Bean。这种“约定优于配置”的理念显著提升了开发效率。本文将深入解析Spring Boot Starter的自动装配原理,涵盖其核心机制、实现流程、自定义方法及最佳实践。

专注于与编程相关的知识内容分享 2470

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

【SpringBoot】深入剖析 Spring Boot 自动装配原理(附源码与实战)

Bean而在 Spring Boot 中,这些 Bean可以不写,Spring Boot 会自动装配合适的 Bean。例如,添加依赖后,Spring Boot 会自动配置DataSource但我们从未在代码中显式定义它!假设我们希望 Spring Boot在项目启动时自动装配一个自定义的 HelloService,而无需手动配置 Bean,我们可以按照以下步骤实现。如果不想让某些自动配置生效,可以使用exclude或者在Spring Boot 通过和加载中的自动配置类。自动配置类使用。

工一木子 1411

Spring Boot 自动装配原理深度解析

自动装配(Auto Configuration)Spring Boot 根据当前项目的依赖、环境和配置,自动为应用配置合适的 Spring 组件。“你引什么依赖,我就帮你配什么 Bean。Spring Boot 通过 @EnableAutoConfiguration 加载自动配置类,并借助条件注解按需向容器中注册 Bean。

2401_88153531的博客 988
上一篇: java使用minio上传大文件
下一篇: 一文带你复习Redis基础命令
java烤冷面
博客等级 码龄4年 177粉丝 29原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值