springboot启动流程、日志分析

SpringBoot应用启动后自动退出?10种原因与系统化排查指南 在Java应用开发中,应用生命周期管理是核心基础概念,它决定了程序何时启动、运行和终止。其原理基于JVM的线程模型:当所有非守护线程结束时,JVM便会正常退出。SpringBoot框架通过自动装配和嵌入式Servlet容器等技术,极大地简化了Web应用的部署与运维。对于开发者而言,理解线程模型与框架生命周期机制的协同工作具有重要技术价值,能有效避免在微服务、后台任务等应用场景中遇到应用意外退出的问题。本文将聚焦于SpringBoot项目中常见的“静默退出”现象,即应用启动后立即正常关闭(exit code 阅读详情

springboot启动流程、日志分析

只关注info级别日志

1. 主类启动,通过调用SpringApplication#run(Class<?> primarySource, String... args)方法启动程序

public static void main(String[] args) {
    SpringApplication.run(AppConfig.class, args);
}

2. SpringApplication实例化、并调用run(Class<?>[] primarySources, String[] args)方法启动

public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
    return run(new Class<?>[] { primarySource }, args);
}

public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
    // 创建创建 SpringApplication 对象并启动
    return new SpringApplication(primarySources).run(args);
}

2.1. 创建SpringApplication对象

主要设置应用类型、初始化器、监听器

public SpringApplication(Class<?>... primarySources) {
    this(null, primarySources);
}

@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    this.resourceLoader = resourceLoader;
    Assert.notNull(primarySources, "PrimarySources must not be null");
    this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    this.webApplicationType = WebApplicationType.deduceFromClasspath();
    setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    this.mainApplicationClass = deduceMainApplicationClass();
}
  • resourceLoader:资源加载器,无默认值,此处即为null,用途参考文章:IoC 之 Spring 统一资源加载策略
  • primarySources:主要的Java Config 类的数组,此处即为服务启动的主类cn.javadog.demo.springboot.AppConfig
  • webApplicationType:Web 应用类型,调用WebApplicationType#deduceFromClasspath()方法,通过classpath推断,此处即为SERVLET
    • 具体类型取决于引入的maven依赖,如果引入的为spring-boot-starter-webflux则类型为REACTIVE,如果引入的为spring-boot-starter-web则类型为SERVLET,都为引入则为null
    • 这个属性,在下面的 createApplicationContext() 方法,将根据它的值(类型),创建不同类型的 ApplicationContext 对象,即 Spring 容器的类型不同。
private static final String[] SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet",
        "org.springframework.web.context.ConfigurableWebApplicationContext" };
private static final String WEBMVC_INDICATOR_CLASS = "org.springframework." + "web.servlet.DispatcherServlet";
private static final String WEBFLUX_INDICATOR_CLASS = "org." + "springframework.web.reactive.DispatcherHandler";
private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer";
private static final String SERVLET_APPLICATION_CONTEXT_CLASS = "org.springframework.web.context.WebApplicationContext";
private static final String REACTIVE_APPLICATION_CONTEXT_CLASS = "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext";

static WebApplicationType deduceFromClasspath() {
    if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
            && !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
        return WebApplicationType.REACTIVE;
    }
    for (String className : SERVLET_INDICATOR_CLASSES) {
        if (!ClassUtils.isPresent(className, null)) {
            return WebApplicationType.NONE;
        }
    }
    return WebApplicationType.SERVLET;
}
  • initializers: ApplicationContextInitializer 数组
    • 通过 getSpringFactoriesInstances(Class<T> type) 方法,进行获得 ApplicationContextInitializer 类型的对象数组,详细的解析,见「2.1.1 getSpringFactoriesInstances」 方法。
    • 当前只在 Spring MVC 的环境下,initializers 属性的结果如下图:
  • listeners:ApplicationListener 数组
    • 也是通过 #getSpringFactoriesInstances(Class type) 方法,进行获得 ApplicationListener 类型的对象数组
    • 当前只在 Spring MVC 的环境下,initializers 属性的结果如下图:
  • mainApplicationClass:程序启动main方法所在的类,此处即为服务启动的主类cn.javadog.demo.springboot.AppConfig
    • 这个 mainApplicationClass 属性,没有什么逻辑上的用途,主要就是用来打印下日志,说明是通过这个类启动 Spring 应用的
private Class<?> deduceMainApplicationClass() {
		try {
			StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
			for (StackTraceElement stackTraceElement : stackTrace) {
				if ("main".equals(stackTraceElement.getMethodName())) {
					return Class.forName(stackTraceElement.getClassName());
				}
			}
		}
		catch (ClassNotFoundException ex) {
			// Swallow and continue
		}
		return null;
	}
2.1.1 从META-INF/spring.factories中指定类对应的实例对象
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
	return getSpringFactoriesInstances(type, new Class<?>[] {});
}

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
	ClassLoader classLoader = getClassLoader();
	// 加载指定类型对应的实现类,去重,在 `META-INF/spring.factories` 里的类名的数组
	Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
	// 创建对象,具体实现不深究
	List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
	// 将对象进行排序,主要是针对类上有`@Order`注解的
	AnnotationAwareOrderComparator.sort(instances);
	return instances;
}

2.2 运行run(String... args)方法启动spring程序,注意是spring程序!

public ConfigurableApplicationContext run(String... args) {
    // <1> 创建 StopWatch 对象,并启动。StopWatch 主要用于简单统计 run 启动过程的时长。
	StopWatch stopWatch = new StopWatch();
	stopWatch.start();
	ConfigurableApplicationContext context = null;
	Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
	// <2> 配置 headless 属性
	configureHeadlessProperty();
	// <3> 获得 SpringApplicationRunListener 的数组,并启动监听
	SpringApplicationRunListeners listeners = getRunListeners(args);
	listeners.starting();
	try {
	     // <4> 创建ApplicationArguments对象
		ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
		 // <5> 加载属性配置。执行完成后,所有的 environment 的属性都会加载进来,包括 application.properties 和外部的属性配置。
		ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
		configureIgnoreBeanInfo(environment);
		// <6> 打印 Spring Banner
		Banner printedBanner = printBanner(environment);
		// <7> 创建 Spring 容器。
		context = createApplicationContext();
		// <8> 异常报告器
		exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
				new Class[] { ConfigurableApplicationContext.class }, context);
	    // <9> 主要是调用所有初始化类的 initialize 方法    
		prepareContext(context, environment, listeners, applicationArguments, printedBanner);
		// <10> 初始化 Spring 容器。
		refreshContext(context);
		// <11> 执行 Spring 容器的初始化的后置逻辑。默认实现为空。
		afterRefresh(context, applicationArguments);
		// <12> 停止 StopWatch 统计时长
		stopWatch.stop();
		// <13> 打印 Spring Boot 启动的时长日志。
		if (this.logStartupInfo) {
			new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
		}
		// <13> 通知 SpringApplicationRunListener 的数组,Spring 容器启动完成。
		listeners.started(context);
		// <14> 调用 ApplicationRunner 或者 CommandLineRunner 的运行方法。
		callRunners(context, applicationArguments);
	}
	catch (Throwable ex) {
	    // <14.1> 如果发生异常,则进行处理,并抛出 IllegalStateException 异常
		handleRunFailure(context, ex, exceptionReporters, listeners);
		throw new IllegalStateException(ex);
	}

    // <15> 通知 SpringApplicationRunListener 的数组,Spring 容器运行中。
	try {
		listeners.running(context);
	}
	catch (Throwable ex) {
	// <15.1> 如果发生异常,则进行处理,并抛出 IllegalStateException 异常
		handleRunFailure(context, ex, exceptionReporters, null);
		throw new IllegalStateException(ex);
	}
	return context;
}
2.2.1 创建 StopWatch 对象,并启动。StopWatch 主要用于简单统计 run 启动过程的时长

逻辑比较简单,就是创建StopWatch对象,其内部有个TaskInfo内部类,记录一次任务的持续时间和任务名称,结果放在StopWatch的taskList属性里;本项目持续时间即为Spring容器初始化的时间,任务名称为空字符串

2.2.2 配置headless属性

这个逻辑,可以无视,和AWT(硬件)相关

2.2.3 获得 SpringApplicationRunListener 的数组,并启动监听

实际类型为SpringApplicationRunListener的实现类EventPublishingRunListener,实现 SpringApplicationRunListener、Ordered 接口,将 SpringApplicationRunListener 监听到的事件,转换成对应的 SpringApplicationEvent 事件,发布到监听器。具体作用暂时不深究

2.2.4 创建ApplicationArguments对象

此处的args目前为空数组!可以通过命令行等方式设置参数

2.2.5 加载属性配置

调用prepareEnvironment(...) 方法,加载属性配置。执行完成后,所有的 environment 的属性都会加载进来,包括 application.properties 和外部的属性配置,具体原理不深究,参见:《【死磕 Spring】—— 环境 & 属性:PropertySource、Environment、Profile》

  • 根据 webApplicationType 类型,会创建不同类型的 ConfigurableEnvironment 对象
  • 主要配置environment有两大属性:propertySources和activeProfiles
    • propertySources:根据配置的 defaultProperties、或者 JVM 启动参数,作为附加的 PropertySource 属性源,本项目都没有做配置
    • activeProfiles:激活的profile,未指定即为空数组,可以同时指定多个
  • 通知 SpringApplicationRunListener 的数组,环境变量已经准备完成,相关监听器会产生一些 debug 级别日志的日志,不去深究
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
	// Create and configure the environment
	// <1> 创建 ConfigurableEnvironment 对象,并进行配置
	ConfigurableEnvironment environment = getOrCreateEnvironment();
	configureEnvironment(environment, applicationArguments.getSourceArgs());
	// <2> 通知 SpringApplicationRunListener 的数组,环境变量已经准备完成。
	listeners.environmentPrepared(environment);
	// <3> 绑定 environment 到 SpringApplication 上,暂时不太知道用途。
	bindToSpringApplication(environment);
	// <4> 如果非自定义 environment ,则根据条件转换。认情况下,isCustomEnvironment 为 false ,所以会执行这块逻辑。但是,一般情况下,返回的还是 environment 自身,所以可以无视这块逻辑先。
	if (!this.isCustomEnvironment) {
		environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment, deduceEnvironmentClass());
	}
	// <5> 如果有 attach 到 environment 上的 MutablePropertySources ,则添加到 environment 的 PropertySource 中。
	ConfigurationPropertySources.attach(environment);
	return environment;
}
2.2.6 打印 Spring Banner

打印的第一个日志,样式如下
banner

  • 默认的是org.springframework.boot.SpringBootBanner打印的spring的启动banner
  • 核心逻辑如下,没有自定义的banner就取默认的,可以通过在路径下添加banner.txt或者指定spring.banner.location属性进行更换
private Banner getBanner(Environment environment) {
	Banners banners = new Banners();
	banners.addIfNotNull(getImageBanner(environment));
	banners.addIfNotNull(getTextBanner(environment));
	if (banners.hasAtLeastOneBanner()) {
		return banners;
	}
	if (this.fallbackBanner != null) {
		return this.fallbackBanner;
	}
	return DEFAULT_BANNER;
}
2.2.7 调用createApplicationContext()创建 Spring 容器

具体解析见下方

2.2.8 创建异常报告器

此处exceptionReporters属性如下,不做深究:

2.2.9 调用 prepareContext(...) 方法,主要是调用所有初始化类的 initialize(...) 方法
private void prepareContext(ConfigurableApplicationContext context,
        ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
        ApplicationArguments applicationArguments, Banner printedBanner) {
    // <1> 设置 context 的 environment 属性
    context.setEnvironment(environment);
    // <2> 设置 context 的一些属性
    postProcessApplicationContext(context);
    // <3> 初始化 ApplicationContextInitializer
    applyInitializers(context);
    // <4> 通知 SpringApplicationRunListener 的数组,Spring 容器准备完成。
    listeners.contextPrepared(context);
    // <5> 打印日志
    if (this.logStartupInfo) {
        logStartupInfo(context.getParent() == null);
        logStartupProfileInfo(context);
    }
    // Add boot specific singleton beans
    // <6> 设置 beanFactory 的属性
    ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
    if (printedBanner != null) {
        beanFactory.registerSingleton("springBootBanner", printedBanner);
    }
    if (beanFactory instanceof DefaultListableBeanFactory) {
        ((DefaultListableBeanFactory) beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
    }
    // Load the sources
    // <7> 加载 BeanDefinition 们
    Set<Object> sources = getAllSources();
    Assert.notEmpty(sources, "Sources must not be empty");
    load(context, sources.toArray(new Object[0]));
    // <8> 通知 SpringApplicationRunListener 的数组,Spring 容器加载完成。
    listeners.contextLoaded(context);
}
2.2.10 调用 refreshContext(ConfigurableApplicationContext context) 方法,启动(刷新) Spring 容器

具体解析见下方

2.2.11 调用afterRefresh(...) 方法,执行 Spring容器的初始化的后置逻辑。 默认实现为空。代码如下:
protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {
}
2.2.12 停止 StopWatch 统计时长
2.2.13 打印 Spring Boot 启动的时长日志。效果如下:
2.2.14 调用 SpringApplicationRunListeners#started(ConfigurableApplicationContext context) 方法,通知 SpringApplicationRunListener 的数组,Spring 容器启动完成
2.2.15 调用 SpringApplicationRunListeners#running(ConfigurableApplicationContext context) 方法,通知 SpringApplicationRunListener 的数组,Spring 容器运行中
ELK处理 SpringBoot 日志,真实太妙了! 在排查线上异常的过程中,查询日志总是必不可缺的一部分。现今大多采用的微服务架构,日志被分散在不同的机器上,使得日志的查询变得异常困难。工欲善其事,必先利其器。如果此时有一个统一的实时日志分析平台,那可谓是雪中送碳,必定能够提高我们排查线上问题的效率。本文带您了解一下开源的实时日志分析平台 ELK 的搭建及使用。 ELK 简介 ELK 是一个开源的实时日志分析平台,它主要由 Elasticsearch、Logstash 和 Kiabana 三部分组成。 Logstash Logstash 主要用.. 阅读详情

相关推荐

波克 上海 Unity开发笔试题 2024

主要分为四部分,如果没有准备好,不要点击笔试链接,进入就会自动开始。

z2014z的博客 3416

SpringBoot源码学习(一)启动

SpringBoot启动流程 框架的初始化 框架的启动 自动化装配 入口 SpringApplication.run(CoreFacadeApplication.class, args); 然后调用 public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return new SpringApplication(primarySources

青鸟飞鱼 387

pytorch转onnx转paddlepaddle

1.pt转onnx 可查看我之前的文章:https://blog.csdn.net/oyjwin/article/details/117778583?spm=1001.2014.3001.5501

oyjwin的博客 1467

Spring boot日志配置

在 src/main/resources/下创建配置文件 logback-spring.xml。上面的配置引入了 spring boot 中 logback 的默认配置和 CONSOLE 追加器,并定义了 root 的日志级别为 info。

爱琴孩的博客 4734

mot_challenge官方评估代码

mot_challenge官方代码使用介绍 评估mot17验证集:每个视频序列的后一半帧作为验证集 下载源码:git clone https://hub.fastgit.org/JonathonLuiten/TrackEval.git 官网上下载data样例,放在TrackEval/下,结构如下: data |-- gt | |-- bdd100k | |-- davis | |-- kitti | |-- mot_challenge | | |-- MOT15-train |

qq_37866436的博客 4902

解决开着代理情况下pip或魔搭下载失败

最近由于经常配环境导致,老是要来回切clash关掉代理,非常的不方便如下面的,魔搭模型下载失败如下面的,pip换源后下载失败。

风吹落叶的博客 2950

SpringBoot启动配置原理

SpringApplication.run(SpringbootDay06Application.class, args); //先创建SpringApplication再运行run 1、创建SpringApplication对象 initialize(sources); private void initialize(Object[] sources) { //保存主配置类 ...

qq_44706044的博客 269

“快速掌握Vivado FPGA开发流程“——详解Vivado开发流程及实例

快速掌握Vivado FPGA开发流程”——详解Vivado开发流程及实例FPGA技术在现代电子领域中应用越来越广泛,而Vivado作为业界最流行的FPGA设计工具之一,也受到越来越多人的关注和使用。那么如何快速掌握Vivado FPGA开发流程呢?本文将详细介绍Vivado开发流程,并通过实例来加深您的理解。首先,我们需要了解Vivado开发流程的主要步骤:创建工程、设计电路、约束电路、生成比特流。接下来,让我们一步步了解这些步骤。

2301_78484069的博客 736

SpringBoot源码解析-启动流程

//todo

Jak的博客 677

【AlphaFold2】深入浅出,讲解Evoformer|学习笔记

本篇博客是围绕youtube德国博主Kilian Mandon()的《从头实现AlphaFold2:AlphaFold Decoded》的第五期视频讲解和note-book内容写成的笔记,加上了自己的理解和对相关概念的解释。上期我们讲解了AlphaFold2的特征提前的部分【AlphaFold2】Feature extraction:提取特征,为模型输入做准备|Datapipeline讲解。本期,我们将介绍AlphaFold2中最为庞大且最为重要的部分——Evoformer。

Yaoyao2024的博客 2020

2026华为OD机考新系统真题 + 双机位C卷 + 往年真题 - 题库目录分值说明 + 考点说明+在线OJ

2026年4月1日起,华为OD机试正式切换至新系统模式!采用力扣模式,无需自己写输入! 难度大幅度降低。正在备考华为OD机试的同学,优先刷新系统机试真题,可大幅提升通过率。 新系统考题考点与旧版一致,无需重新适应。本专栏所有算法题均配有详细思路解析,并提供C语言、JS、C++、Python、Go、Java多语言源码实现。订阅后私信即可开通专属OJ刷题权限,高效备考一次上岸!

算法大师! 45万+

《SpringBoot启动流程三》:两万+字图文带你debug源码分析SpringApplication准备阶段(含配置文件加载时机、日志系统初始化时机)

图文带你debug源码分析SpringApplication准备阶段 1、配置文件的加载时机? 2、日志系统初始化时机? 3、Spring Boot prepareContext()源码解析 4、Spring Boot prepareEnvironment()源码解析

健身变秃,coding变强 6382

PyTorch深度学习实战(7)——批大小对神经网络训练的影响

在神经网络中,批( batch )是指一次输入网络进行训练或推断的一组样本。批处理( batch processing )是指将这一组样本同时输入网络进行计算的操作。本节中首先介绍批( Batch )的基本概念,并且介绍批大小在神经网络训练过程中的影响。

盼小辉丶的博客 1万+

Spring Boot启动类与启动过程

/ 1. 最常用// 2. 排除自动配置.run(args);// 3. 自定义 Banner(resources/banner.txt).run(args);// 4. Fluent API 方式(推荐!.run(args);// 5. 完全编程式(微服务网关常用)// 改成响应式// 6. 自定义监听器。

m0_57545130的博客 1042

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

SpringBoot配置ELK日志分析系统搭建

SpringBoot配置ELK日志分析系统搭建 ELK介绍 Logstash:日志收集工具,可以从本地磁盘,网络服务(自己监听端口,接受用户日志),消息队列中收集各种各样的日志,然后进行过滤分析,并将日志输出到Elasticsearch中。 Elasticsearch:日志分布式存储/搜索工具,原生支持集群功能,可以将指定时间的日志生成一个索引,加快日志查询和访问。 Kibana:可视化日志Web展示工具,对Elasticsearch中存储的日志进行展示,还可以生成炫丽的仪表盘。 环境配置 准备工作 首

别当程序员的博客 1407

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

SpringBoot源码阅读方法论:启动流程、自动配置与实战排查

源码阅读能力是后端工程师从熟练使用走向原理级理解的桥梁。掌握框架的启动与装配逻辑,能显著提升排查复杂问题的效率。以SpringBoot为例,其启动流程、自动配置与条件注解构成一条清晰的主线:从SpringApplication.run()入口,经过环境准备、容器刷新,到AutoConfigurationImportSelector加载候选配置,再通过@Conditional条件过滤实现按需装配。理解这些机制,不仅能够解释“自动配置不生效”、“Bean未创建”等高频故障,还能将CGLIB代理、SPI扩展等知识

weixin_32288959的博客 284

深度学习工具包 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")

AI如何帮你快速解决Spring Boot启动错误

现在遇到Spring Boot启动问题,我的第一反应不再是全网搜索,而是先让AI助手帮忙分析核心矛盾。这种开发方式既节省时间,又能学到更系统的问题解决方法。尝试用AI辅助解决这类问题,发现效率提升非常明显。这里分享我的实践经验,希望能帮大家少走弯路。整个过程从发现问题到获得解决方案不到30秒,比手动排查快了一个数量级。这个过程既耗时又容易遗漏关键信息,尤其对新手来说门槛较高。时,很多开发者会陷入漫长的排查过程。遇到Spring Boot启动报错。

SilverfoxOwl19的博客 414

从日志入手:SpringBoot中Quartz(v2.3.2)的完整启动流程解析与关键节点调试技巧

本文深入解析SpringBoot中Quartz(v2.3.2)的完整启动流程,通过日志分析和关键节点调试技巧,帮助开发者快速定位任务不执行、调度延迟等问题。文章详细介绍了初始化阶段、启动阶段的核心链路调试方法,以及线程模型与任务调度机制,为高效调试Quartz提供实用指南。

u5v6w7的博客 815

SpringBoot启动报错BeanDefinitionStoreException解析与解决方案

Spring框架中的IoC容器是依赖注入的核心机制,负责管理应用中各个组件的生命周期和依赖关系。当容器在初始化过程中遇到无法加载或解析bean定义的情况时,会抛出BeanDefinitionStoreException异常。这类问题通常源于配置错误、依赖冲突或资源加载问题,是Spring应用开发中的常见痛点。通过分析异常堆栈中的Caused by信息,开发者可以快速定位问题根源。解决方案包括检查XML/注解配置的正确性、使用Maven Helper分析依赖树冲突、以及启用DEBUG级别的Spring日志输出

weixin_31292729的博客 272

SpringBoot自动配置与JVM分代GC深度解析

自动配置是SpringBoot框架的核心特性,通过条件装配机制实现约定大于配置的开发体验。其原理基于@Conditional系列注解对类路径、Bean存在性和配置属性进行动态判断,结合SpringFactoriesLoader实现组件自动注册。这种机制大幅提升了Java应用的开发效率,特别适合微服务架构中的标准化组件集成。在JVM层面,分代垃圾回收通过Eden、Survivor和老年代的分区设计,配合不同GC算法实现内存高效管理。理解这些底层机制对优化高并发场景下的应用性能至关重要,例如通过调整-XX:Ne

chengyixian7877的博客 337

JavaEE-Spring 环境配置(项目创建步骤)

网页版创建SpringBoot项目。

qq_43570634的博客 332

IntelliJ IDEA运行SpringBoot项目:从环境配置到启动排错全攻略

在Java后端开发中,IDE、JDK和Maven构成了项目运行的基石。理解这三者的分工与协作原理,是高效开发的前提:JDK负责编译,Maven管理依赖,而IDEA将这些能力整合为图形化操作界面。正确配置构建工具链,能显著提升项目创建与调试的效率。实际开发中,无论是创建SpringBoot项目时的依赖下载缓慢,还是运行时的端口占用、版本不兼容等问题,都源于环境配置不当。掌握Maven镜像源、JDK版本匹配以及IDEA的项目结构设置,即可快速解决这些常见工程实践难题。从新建项目、配置运行环境,到启动调试与排查报

weixin_29290947的博客 226

SpringBoot+Nacos+MySQL微服务问题排查指南

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能。以下内容适用于 Spring Boot + Nacos + MySQL 微服务架构 的常见问题(如启动失败、连接超时、配置未加载等)。项目地址:https://github.com/YunaiV/ruoyi-vue-pro。视频教程:https://doc.iocoder.cn/video/

芋艿V 95

SpringBoot整合MyBatis:从“Consider defining a bean”报错剖析@MapperScan与@Mapper的配置陷阱

本文深入解析SpringBoot整合MyBatis时常见的'Consider defining a bean'报错问题,重点剖析@MapperScan与@Mapper的配置差异及常见陷阱。通过实战案例展示路径拼写错误、注解冲突等典型问题的解决方案,并提供多模块项目配置建议与DEBUG日志排查技巧,帮助开发者高效解决MyBatis的bean注册问题。

weixin_27013291的博客 388

Spring Boot+MyBatis启动报错:sqlSessionFactory或sqlSessionTemplate缺失的完整排查指南

Spring Boot应用启动时,Bean的初始化失败常常源于依赖缺失或配置失效。在MyBatis整合场景中,SqlSessionFactory作为会话工厂,负责生产SqlSession并管理Mapper绑定;SqlSessionTemplate则提供Spring风格的模板封装。当容器中两者皆无,MapperFactoryBean在初始化校验时便会抛出Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required。这一报错看似简单,背后却隐

weixin_34072296的博客 223

Springboot集装箱管理系统项目从零跑通到二次开发完整指南

Spring Boot作为Java企业级开发的主流框架,凭借自动配置和内嵌容器大幅降低了项目搭建门槛。理解其核心原理——从控制器到服务层再到持久层的调用链,以及配置文件(数据源、端口)与依赖版本的一致性,是快速部署任何Spring Boot项目的基础。在实际工程中,以集装箱管理系统这类典型业务为例,完整的落地流程涉及数据库脚本导入、Maven依赖拉取、IDE调试及打包部署等环节。掌握这套标准化的运行与排错路径,不仅能让源码项目顺利启动,也为二次开发与生产部署奠定坚实基础。

weixin_33462167的博客 207
上一篇: Java实现控制台打印进度条效果
bug斗罗
博客等级 码龄10年 8粉丝 29原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址