spring源码解读-3.初始化维护依赖关系

Springboot源码分析之Spring循环依赖揭秘 摘要: 若你是一个有经验的程序员,那你在开发中必然碰到过这种现象:事务不生效。或许刚说到这,有的小伙伴就会大惊失色了。Spring不是解决了循环依赖问题吗,它是怎么又会发生循环依赖的呢?,接下来就让我们一起揭秘Spring循环依赖的最本质原因。 Spring循环依赖流程图 Spring循环依赖发生原因 使用了具有代理特性的BeanPostProcessor 典型的有 事务注解@Transac... 阅读详情

上一节我们知道spring创建bean实例的源码所在了。那么现在来看看它是如何对bean进行初始化,维护它的依赖的;
这里维护依赖其实有多种方式,比如构造器注入,注解注入,一种是set赋值的方式;今天看的自动注入的类型的非构造器类型的;
先把图补充一下:
这里的红色箭头就是今天的重点。就是通过它来查找依赖的;
在这里插入图片描述

这里还得回去去看那个doCreateBean的代码;
路标1:回看doCreateBean()->populateBean():

	protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		//到这里bean已经实例化出来了存在instanceWrapper的包装中
		final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
		Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		//用于解决循环依赖的,先不看
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isDebugEnabled()) {
				logger.debug("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			addSingletonFactory(beanName, new ObjectFactory<Object>() {
				@Override
				public Object getObject() throws BeansException {
					return getEarlyBeanReference(beanName, mbd, bean);
				}
			});
		}

		// Initialize the bean instance.
		Object exposedObject = bean;
		//初始化逻辑就在这里面
		try {
		//属性赋值
			populateBean(beanName, mbd, instanceWrapper);
			if (exposedObject != null) {
		//初始化完成,进行一系列的通知
				exposedObject = initializeBean(beanName, exposedObject, mbd);
			}
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
			}
		}

		if (earlySingletonExposure) {
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						throw new BeanCurrentlyInCreationException(beanName,
								"Bean with name '" + beanName + "' has been injected into other beans [" +
								StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
								"] in its raw version as part of a circular reference, but has eventually been " +
								"wrapped. This means that said other beans do not use the final version of the " +
								"bean. This is often the result of over-eager type matching - consider using " +
								"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
					}
				}
			}
		}

		// Register bean as disposable.
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}

路标2:populateBean()
在这个方法里面就是对bean的实例进行属性赋值的地方;这里面也就是spring帮你维护依赖关系的一个地方;代码中可以找到根据名字或者类型进行自动注入的逻辑;

	protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
		PropertyValues pvs = mbd.getPropertyValues();

		if (bw == null) {
			if (!pvs.isEmpty()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				// Skip property population phase for null instance.
				return;
			}
		}

		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		boolean continueWithPropertyPopulation = true;
		//执行一些生命周期的钩子
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}

		if (!continueWithPropertyPopulation) {
			return;
		}
		//判断是否有需要自动注入的逻辑
		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

			// Add property values based on autowire by name if applicable.
			//根据名称进行注入
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}

			// Add property values based on autowire by type if applicable.
			//根据类型注入
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}

			pvs = newPvs;
		}

		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

		if (hasInstAwareBpps || needsDepCheck) {
			PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			if (hasInstAwareBpps) {
				for (BeanPostProcessor bp : getBeanPostProcessors()) {
					if (bp instanceof InstantiationAwareBeanPostProcessor) {
						InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
						pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvs == null) {
							return;
						}
					}
				}
			}
			if (needsDepCheck) {
				checkDependencies(beanName, mbd, filteredPds, pvs);
			}
		}

		applyPropertyValues(beanName, mbd, bw, pvs);
	}

路标3:根据beanName注入的方式
是不是看到getBean(propertyName)了;是不是回到当初实例化的时候看过的代码了;这里其实就是去容器中查找依赖,如果有的话就返回给当前创建对象进行引用,如果没有就按照实例化的流程创建一个bean出来,然后放入容器中,并返回给当前创建对象进行引用;到这里就知道了,spring是如何维护依赖关系的;另外一个根据类型来查找的代码请自行研究。今天的就到这里点到即止了;

	protected void autowireByName(
			String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

		String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
		for (String propertyName : propertyNames) {
			if (containsBean(propertyName)) {
				Object bean = getBean(propertyName);
				pvs.add(propertyName, bean);
				registerDependentBean(propertyName, beanName);
				if (logger.isDebugEnabled()) {
					logger.debug("Added autowiring by name from bean name '" + beanName +
							"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
				}
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
							"' by name: no matching bean found");
				}
			}
		}
	}

总结: 这些代码上来只是粗略看,一定不要在细枝末节上死抠。你要首先有一个大的脉络;之后再根据大脉络各个击破细节难点。这样有了一个宏观的方向之后想找哪部分的逻辑就很容易了

Spring AOP源码解读 aop 是什么 AOP (Aspect-Oriented Programming,面向切面编程),可以说是 OOP 的补充和完善。OOP 引入封装、继承和多态性等概念来建立一种对象层次结构,用以模拟公共行为的一个集合。当我们需要为分散的对象引入公共行为的时候,OOP 则显得无能为力。OOP 允许你定义从上到下的关系,但并不适合定义从左到右的关系。例如日志功能。日志代码往往水平地散布在所有对象层次中,而与它所散布到的对象的核心功能毫无关系。对于其他类型的代码,如安全性、异常处理和透明的持续性也是如此。这种散布 阅读详情

相关推荐

4-Spring架构源码分析-Spring IOC机制设计思想和源码解读

被注入的对象需要什么,直接跟IoCServiceProvider打声招呼,后者就会把相应的被依赖对象注入到被注入的对象中,从而达到IoCServiceProvider为被注入对象服务的目的。相比于构造器注入,setter方式注入会显得比较宽松灵活些,它可以在任何时候进行注入(当然是在使用依赖对象之前),这就好比你可以先把自己想要的妹子想好了,然后再跟婚介公司打招呼,你可以要林志玲款式的,赵丽颖款式的,甚至凤姐哪款的,随意性较强。,用来描述Spring中的Bean对象。...

Java架狗师知识框架速查表 229

聊透Spring循环依赖

在探讨Spring循环依赖的解决方式以前,我们先来回忆一下什么是循环依赖:A依赖B的同时,B也依赖了A,就构成了循环依赖。依赖关系如下图所示:@Component// 依赖Breturn b;}}@Component// 依赖Areturn a;}}//比较特殊的循环依赖@Component// 依赖B}复制代码当然也有一些链路较长,隐藏的比较深的循环依赖,比如:A -> B -> C -> D -> ... -> B这种,无论如何,都要形成一个环才能被称为循环依赖。

lt_xiaodou的博客 822

Jive论坛源码解读与二次开发指南

Jive是一个功能丰富的在线论坛软件,它提供了一个平台,使用户能够围绕不同的主题和兴趣点交流意见和信息。Jive的用户界面是灵活的,允许轻松创建和管理多个论坛,这使得它成为各种组织和社区的理想选择。Jive论坛的源码目录结构是其整个系统组织的重要表现,它反映了Jive论坛的模块化设计思想和开发过程的条理。核心的源码目录大致可以分为以下几个部分:src:存放所有的Java源代码文件。webapp:包括了JSP页面、CSS样式表、JavaScript脚本以及HTML文件等Web资源。

weixin_42608299的博客 1207

Spring--解决@Async导致的循环依赖失败问题

本文介绍Spring中的@Async导致循环依赖失败的原因及其解决方案。

IT利刃出鞘的博客 1908

Kubernetes集群资源优化实战:Volcano调度器如何帮你省下30%GPU算力

本文详细介绍了如何通过Volcano调度器的Binpack策略优化Kubernetes集群中的GPU资源利用率,解决AI模型训练中的资源碎片化问题。通过实战配置和调优指南,帮助用户提升30%的GPU算力利用率,显著降低任务等待时间和硬件成本。

weixin_30832143的博客 507

3GPP协议解读_NTN系列(一)_38.811_非地面网络(NTN)的背景、应用场景和信道建模

非地面网络覆盖广,对物理攻击和自然灾害有一定的抵抗性。本文根据3GPP协议对NTN网络的背景、应用场景和信道模型进行了整理。

JCMLSY的博客 4927

年薪50万的一个面试题,看着不难,却刷掉了90%的人(2),2024年最新程序员面试技巧

1:通过addSingletonFactory用于将早期的bean暴露出去,主要是将其丢到第3级缓存中,代码如下://第1级缓存中不存在beanif (!//将其丢到第3级缓存中//后面的2行代码不用关注上面的方法执行之后,serviceA就被丢到第3级的缓存中了。

616

基于CRU和WorldClim的高分辨率(1km)气候数据生成

基于CRU和WorldClim的高分辨率(1km)气候数据生成

lhq7842955的博客 1693

【spring学习笔记 七】循环依赖解决思路

文章目录问题解决方案非正常表现解决方案 这章我们主要来聊聊在doCreateBean()方法中,`spring是如何解决循环依赖的,以及一些错误的使用方式。 问题 假设现在我们有两个类,分别是A类,B类,同时A类需要引用B类,B类需要引用A类,也就是套娃模式。 @Component public class A { @Autowired private B b; } @Component...

唐芬奇的博客 813

Vlan的封装模式和端口讲解(Access、Trunk、Hypbrid端口)

Vlan(Virtual Local Area Network)虚拟局域网,将一个物理的LAN在逻辑上划分为多个广播域,在交换机上实现广播域隔离(增强局域网的安全性、限制广播风暴、简化网络管理)Vlan通过将二层数据帧打上Vlan标签(打上Vlan标签也就是封装Vlan),正常情况下,不同Vlan Tag的数据包是无法二层直接互访的,以此来实现广播域的隔离可以理解为一个Vlan对应一个广播域,同一Vlan内的主机可以二层直接通信,不同Vlan间的主机无法二层直接通信。

m0_49864110的博客 5643

【AI智能体】Dify 搭建个人专属简历美化助手操作详解

Dify 搭建个人专属简历诊断助手实战操作详解

congge 4381

Spring容器初始化源码解析

Spring框架被广泛应用于我们的日常工作中,但是很长时间以来我们都是只会使用,不懂它的作用原理。通过最近一段时间的阅读源码,个人发现通过阅读源码,能够帮助我们了解Spring的设计理念,并且对Java编程中的一些设计模式更加熟悉,所以记录一下自己对Spring源码的理解。 在开始进行源码学习前,首先再回顾一下三种Spring编程风格: 1、基于Schemal,即通过xml标签的配置方式 2、基于Annotation的注解技术,使用@Component等注解配置bean 3、基于Java Confi

890

Python爬虫实战:基于Playwright与异步技术的专利数据抓取系统

专利数据是企业技术创新、市场竞争分析和行业趋势预测的关键情报来源。然而,专利数据通常分散在各个国家的专利局网站,数据结构复杂,反爬机制严格,使得高效抓取成为技术挑战。本文将详细介绍如何构建一个基于最新Python技术的专利数据抓取系统,涵盖Selenium的现代化替代方案Playwright、异步编程、智能代理轮换等高级技术。

2201_76125261的博客 1562

Spring框架中Bean是如何加载的?从底层源码入手,详细解读Bean的创建流程

从底层源码入手,通过代码示例,追踪AnnotationConfigApplicationContext加载配置类、启动Spring容器的整个流程,并对IOC、BeanDefinition、PostProcesser等相关概念进行解释

种一棵树最好的时间是十年前,其次是现在 3975

从传感器到执行-智能家居 Agent 的感知-决策-执行闭环

本文提出了一种面向智能家居的感知型Agent架构,通过"感知-决策-执行"的闭环系统实现智能化控制。感知模块整合多源传感器数据,决策模块基于规则或机器学习模型生成控制策略,执行模块完成设备操作。系统能够实时监测环境参数和用户状态,自动调节温度、照明等设备,提升家居舒适度。该架构可扩展为多模态感知与强化学习相结合的智能系统,为智慧家居发展提供技术基础。

一键难忘的博客 1122

【异常】Milvus向量数据库的常见错误“collection not loaded“(集合未加载)

Milvus数据库报错"collection not loaded"分析及解决方案。该错误发生在对未加载的集合执行查询操作时,核心原因是集合创建后需先加载到内存才能使用。解决方案包括:1)确认集合是否存在;2)查询前调用loadCollection接口加载集合;3)处理加载超时或失败情况,可检查加载状态;4)确保Milvus服务正常运行。建议在长期不使用集合时释放内存资源。文末附Java代码示例说明具体操作方法。

奶爸的编程之路,也就一周冷个三天 380

Spring源码解读——开篇

Spring源码解读——开篇

m0_67692587的博客 996

深度学习工具包 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&#39;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(&#39;DeepLearnToolbox&#39;));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(&#39;state&#39;,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&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,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 = &#39;sigm&#39;;%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, &#39;Too big error&#39;);```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(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;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)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;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, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% 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&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 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, &#39;Too big error&#39;);```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(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % 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, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);%% 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(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

四、Spring是如何初始化Bean的实例

文章目录一、回顾BeanDefinition注册1.BeanDefinition是什么?2.注册BeanDefinition逻辑回顾3.为什么回顾BeanDefinition注册相关内容?二、Bean的实例化过程1.Bean实例化方法入口描述2.图解Bean实例化流程3.论BeanPostProcessor4.源码解析Bean的实例化过程4.1 找到入口代码4.2 不断的getBean直到doGetBean4.3 不断的createBean最后doCreateBean4.4 有参和无参构造函数的初始化4.5

书生不读四书五经 1426

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Spring源码分析(一)Spring的初始化和XML解析

前言 Spring是什么?它是一个应用程序框架,为应用程序的开发提供强大的支持,例如对事务处理和持久化的支持等;它也是一个bean容器,管理bean对象的整个生命周期,维护bean的各种存在状态,例如bean对象的实例化、销毁、bean的单实例和多实例状态等。 Spring作为Java发展史上不可忽视的存在,说他重新定义了Java也不为过。它功能强大,着实为日常开发提供了大大的便利。表面越简单的东...

七夜zippoe的博客 327

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

深度解析 Spring 源码:揭秘 AbstractAutowireCapableBeanFactory 的 Bean 生命周期处理

本文深入解析了 Spring 框架中的核心组件之一AbstractAutowireCapableBeanFactory,重点揭秘了其在 Bean 生命周期处理中的关键作用。首先,我们探讨了 Spring IoC(控制反转)和 DI(依赖注入)的基本原理,以及 AbstractAutowireCapableBeanFactory 在其中的地位和作用。通过本文的阐述,读者将深入了解 Spring 框架中 Bean 的生命周期处理机制,为进一步理解和应用 Spring 框架提供了重要参考。

忆~遂愿的博客 2800

Spring源码解读:解决循环依赖的三种方式

循环依赖,通常指的是在Spring容器中的Bean之间形成了环形的依赖关系。例如,Bean A依赖于Bean B,而Bean B又依赖于Bean A,或者更复杂的情况下,多个Bean相互之间形成闭环依赖。本文深入分析了Spring解决循环依赖的三种主要方式:构造器注入、Setter注入和使用注解。每种方式都有其适用场景和特点,开发者在选择时应根据实际情况和需求做出最佳决策。@Lazy。

GZM888888的博客 542

深入浅出解读 Spring 源码:IOC/AOP 篇

BeanFactory 是 IOC 容器的最基本接口,提供了最简单的 IOC 容器的实现,而 ApplicationContext 是 BeanFactory 的一个子接口,提供了更多的功能,包括 AOP、事件传递、国际化等。本文主要介绍的是 Spring AOP,它是 Spring 框架中的一个模块,提供了对 AOP 的支持。前置增强是在目标方法执行前执行的操作,后置增强是在目标方法执行后执行的操作,环绕增强是在目标方法执行前后都执行的操作,异常增强是在目标方法抛出异常时执行的操作。

good7ob的博客 268

JAVA资深架构师成长路线->开源框架解读->SpringMVC框架源码解读

文章目录JAVA资深架构师成长路线大纲SpringMVC框架源码解读Servlet3.0ServletContainerInitializer容器初始化ServletRegistration注册FilterRegistration过滤器ServletContext性能实战基于Servlet3.0异步Callable异步DeferredResult异步SpringMVC面试锦囊 JAVA资深架构师成...

weixin_42213903的博客 462

第一章 基于Spring Framework 5.1.3 探索Spring的启动流程

----开篇言:由于自己才疏学浅,加上入行两年多的时间了,如果还停留在if else的阶段,不去深入了解一款框架,不去深入学习一些源码,不去探索一些设计思想,那么自己的核心竞争力就约等于0 。打算利用这两天,深度分析一下Spring Framework框架启动机制与IOC、AOP的底层设计思想,还有著名的Dubbo框架的信息流转方式与底层netty的交互方式,还有Reactor的一些设计思路。 ...

LJHSkyWalker的博客 952

spring-02 IOC容器设计理念与源码解读

Spring Framework 开发参考手册.chm 1.Ioc理论概要 在JAVA的世界中,一个对象A怎么才能调用对象B?通常有以下几种方法。 类别 描述 时间点 外部传入 构造方法传入 属性设置传入 设置对象状态时 运行时做为参数传入 调用时 内部创建 属性中直接创建 创建引用对象时 初始化方法创建 创建引用对象时 运行时动态创建 调用时 上...

沐宇熙IT成长之路 1226

爱恨交错的Spring(AnnotationConfigApplicationContext源码解析)

首先说一下关于Spring的源码,花了很久的时间、不停的反复查看资料和手写笔记以及总结、还只是明白了Spring源码当中的一小部分、最后总结出来一句话就是:Spring的源码 真的真的真的 很难读 Spring内部之间维护的关系,Spring大师写代码的思维逻辑,如果没有人引导你的话,你可能会掉进这个Spring的深渊,让你在这个深渊里面越陷越深(让你在Spring源码里面不停的绕,思维卡带,代码...

qq_34950401的博客 201
上一篇: spring源码解读-2.根据图纸创建bean实例
下一篇: spring源码解读-4.把创建的bean丢到容器中
掀衣怒码
博客等级 码龄6年 6粉丝 19原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值