Spring boot 异常配置

SpringBoot全局异常处理+Slf4j日志文件配置 做任何事情都要用心,要非常关注细节。看起来不起眼的、繁琐的工作做透了会有意想不到的价值。当然要想成为一个技术大牛也需要一定的思想格局,思想决定未来你要往哪个方向去走, 建议多看一些人生规划方面的书籍,多学习名人的思想格局,未来你的路会走的更远。更多的技术点思维导图我已经做了一个整理,涵盖了当下互联网最流行99%的技术点,在这里我将这份导图分享出来,以及为金九银十准备的一整套面试体系,上到集合,下到分布式微服务《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》 阅读详情

Spring boot 异常配置

上一节 Spring boot 参数校验

Spring boot 参数校验

源码

springboot学习指南


直接上代码。。。

1.通过ExceptionHandler 处理控制器异常

1. 局部异常处理
在controller中通过注解@ExceptionHandler 修饰控制器的方法,即可处理本控制器的异常信息;
属性value 指定处理那些异常

@RestController
@RequestMapping("ex")
@Api(tags = {"测试局部异常处理"})
public class TestPartExceptionContorller {

    @GetMapping("ex3")
    @ApiOperation(value = "测试局部异常处理", httpMethod = "GET")
    public void testPartException() throws Exception {
        int i = 1 / 0; // 模拟程序报错
    }

    /*局部异常处理,只处理当前controller的异常信息*/
    @ExceptionHandler(value = {Exception.class})
    public ResponseEntity<ResultBean<Void>> handlerPartException(HttpServletRequest request, HttpServletResponse response, Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ResultBean.result(HttpStatus.INTERNAL_SERVER_ERROR));
    }

}

当 请求 访问到testPartException方法时报错后,我们在handlerPartException 指定了处理Exception的异常,所以报错Exception以及子类异常都会走异常处理方法。

通过@ExceptionHandler 和@RestControllerAdvice (或者@ControllerAdvice) 做全局异常处理

全局默认异常处理

@RestControllerAdvice
public class GlobalExceptionHandler {
    /*默认异常处理*/
    @ExceptionHandler(value = {Exception.class})
    public ResultBean<Void> defExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e, HandlerMethod method) throws Exception {
        String message = e.getMessage();
        log.error("error -- message = " + message, e);
        return ResultBean.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), message);
    }
    ...

通过@RestControllerAdvice 指定本类为异常处理类,另@RestControllerAdvice 的value 或者basePackages 属性可以指定具体那个包下控制器;

方法defExceptionHandler为默认异常处理(因为我们指定了Exception,异常类的基类),如果程序报异常会找到指定的ControllerAdvice中的 标注了@ExceptionHandler方法有哪些能够处理改异常的方法,若没有完全匹配的则找父类一级一级想上找;最终肯定就会找到 Exception 匹配的方法处理。

上一章节 Spring boot 参数校验; 我们进行了参数校验的学习;但是返回的信息不太友好;我们这章通过全局异常处理对校验后的异常进行处理封装,同时也熟悉了全局异常处理的使用方式。

参数校验异常处理

处理MethodArgumentNotValidException 和 ConstraintViolationException 异常信息
这两个异常会在参数校验出错的时候抛出;
MethodArgumentNotValidException: 是实体bean校验出错
ConstraintViolationException: 是基本参数类型(包括string) 校验出错

   /*valid 参数校验异常处理*/
    //MethodArgumentNotValidException  ConstraintViolationException
    @ExceptionHandler(value = {ConstraintViolationException.class, MethodArgumentNotValidException.class})
    public ResponseEntity<ResultBean<Void>> constraintValidatedExceptionHandler(HttpServletRequest request, Exception e, HandlerMethod method) {
        ResponseEntity.BodyBuilder responseEntityBuilder = ResponseEntity.badRequest();
        ResultBean<Void> resultBean = ResultBean.result(HttpStatus.BAD_REQUEST);
        StringJoiner stringJoiner = new StringJoiner(";", "异常信息{ ", " }");
        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) e;
            Optional.ofNullable(constraintViolationException.getConstraintViolations()).orElseGet(HashSet::new)
                    .forEach(v -> {
                        String message = v.getMessage();
                        PathImpl propertyPath = (PathImpl) v.getPropertyPath();
                        String s = propertyPath.getLeafNode().asString();
                        stringJoiner.add(s + ": " + message);
                    });
        }
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
            List<FieldError> fieldErrors = methodArgumentNotValidException.getBindingResult().getFieldErrors();
            Optional.ofNullable(fieldErrors).orElseGet(ArrayList::new).forEach(v -> {
                String field = v.getField();
                String defaultMessage = v.getDefaultMessage();
                stringJoiner.add(field + ": " + defaultMessage);
            });
        }
        resultBean.setMsg(stringJoiner.toString());
        return responseEntityBuilder.body(resultBean);
    }

我们还是使用swagger 进行http调用请求;

请求获取商品详情; 指定了id 的长度

    @ApiOperation(value = "获取商品详情", httpMethod = "GET")
    @GetMapping("product")
    public Product getProduct(@Length(max = 32, min = 32) @RequestParam String id) throws Exception {
        Product product = new Product();
        product.setId(id);
        product.setName("xiaomi 11");
        product.setPrice(199900L);
        return product;
    }

通过swagger 请求;
指定id 为11 不满足参数校验; 不满足会 报异常ConstraintViolationException
在这里插入图片描述
返回信息
code 为400; msg 也是我们封装的信息
在这里插入图片描述
请求添加商品信息
对Product 进行了参数校验;

Product

@ApiModel(description = "商品详情")
public class Product {

   @ApiModelProperty(required = true, value = "商品名称")
   @NotBlank
   @Length(min = 1, max = 500)
   private String name;

   @ApiModelProperty(required = true, value = "商品id")
   @NotBlank
   @Length(max = 32, min = 32)
   private String id;

   @ApiModelProperty(required = true, value = "商品价格,以分为单位", dataType = "java.lang.Long", example = "1000")
   @Max(Integer.MAX_VALUE)
   @Min(0)
   private Long price;

   @ApiModelProperty(required =  true, value = "生产日期", dataType = "date")
   @NotNull
   private Date pdTime;

请求方法

    @ApiOperation(value = "添加商品信息", httpMethod = "POST")
    @PostMapping("product")
    public String addProduct(@Validated @RequestBody Product product) throws Exception {
        return product.getId();
    }

swagger 访问,还是让id的长度不够32; 对java bean的校验这里会报错 MethodArgumentNotValidException 异常
在这里插入图片描述
返回信息
在这里插入图片描述

处理HttpMessageNotReadableException 异常
也是属请求参数的异常信息;当参数类型不对或者解析出错时 会报错HttpMessageNotReadableException; 例如 String转 Integer 传入的参数不是数字,还有Date类型format出错;

  /*参数转换异常处理*/
    @ExceptionHandler(value = {HttpMessageNotReadableException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public HttpEntity<ResultBean<Void>> methodArgumentNotValidExceptionHandler(HttpServletRequest request, HttpMessageNotReadableException e, HandlerMethod method) {
        String localizedMessage = e.getLocalizedMessage();
        ResultBean<Void> resultBean = ResultBean.result(HttpStatus.BAD_REQUEST);
        HttpEntity<ResultBean<Void>> httpEntity = new HttpEntity(resultBean);
        if (localizedMessage.startsWith("JSON parse error")) {
            String through_reference_chain = localizedMessage.substring(localizedMessage.lastIndexOf("through reference chain"));
            String field = through_reference_chain.substring(through_reference_chain.lastIndexOf("[\"") + 2, through_reference_chain.lastIndexOf("\"]"));
            resultBean.setMsg("参数解析出错!请检测参数: " + field);
        }
        return httpEntity;
    }

如上我们还可以通过 @ResponseStatus 指定 http状态码;

swagger 访问我们把日期格式输入错误; pdTime 默认格式应该为 yyyy-MM-dd HH:mm:ss.SSS格式;我们使用yyyy/MM/dd格式传输;
在这里插入图片描述
返回信息
在这里插入图片描述

自定义异常处理

创建业务异常类BusinessException; 处理自定义异常BusinessException

    /*自定义异常处理*/
    @ExceptionHandler(value = {BusinessException.class})
    public void businessExceptionHandler(HttpServletRequest request, HttpServletResponse response, BusinessException e, HandlerMethod method) throws IOException {
        log.error("异常处理: businessException;\n【 远端请求地址:{}; 请求URI:{};" +
                        "\n 请求方法:{}; error message:{}】",
                request.getRemoteHost(), request.getRequestURI(),
                method.getMethod().getName(), e.getLocalizedMessage());
        response.getWriter().write(new ObjectMapper().writeValueAsString(ResultBean.error(e.getCode(), e.getMsg())));
    }

请求方法访问,抛出一个 BusinessException 异常

    @GetMapping("ex")
    @ApiOperation(value = "测试自定义异常处理", httpMethod = "GET")
    public Object testMyException(@RequestParam(required = false) @ApiParam(name = "str", value = "str") String str) throws Exception {
        throw new BusinessException("test businessException", 5001);
    }

swagger 访问;处理自定义异常; 略。。。
总结
上面的示例基本包含了常用的处理方式,@ExceptionHandler 修饰的方法 我们可以返回一个具体的ReusltBean; 或者一个HttpEntity 以及 ResponseEntity; 甚至一个void;


2.通过继承ResponseEntityExceptionHandler 进行全局异常处理

@RestControllerAdvice
public class GlobalExHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        ...
    }

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        ...
    }

    @Override
    protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
     ...
    }
    ...
}

ResponseEntityExceptionHandler中的handleException 处理大部分的异常进行;也是通过 @ExcepitonHandler

	@ExceptionHandler({
			HttpRequestMethodNotSupportedException.class,
			HttpMediaTypeNotSupportedException.class,
			HttpMediaTypeNotAcceptableException.class,
			MissingPathVariableException.class,
			MissingServletRequestParameterException.class,
			ServletRequestBindingException.class,
			ConversionNotSupportedException.class,
			TypeMismatchException.class,
			HttpMessageNotReadableException.class,
			HttpMessageNotWritableException.class,
			MethodArgumentNotValidException.class,
			MissingServletRequestPartException.class,
			BindException.class,
			NoHandlerFoundException.class,
			AsyncRequestTimeoutException.class
		})
	@Nullable
	public final ResponseEntity<Object> handleException(Exception ex, WebRequest request) throws Exception {
	...

所以继承该类 重新指定异常方法即可~


下一节 Spring boot lombok

Spring boot lombok

如何在Spring Boot应用中配置全局异常处理器? 通过以上步骤,就可以在 Spring Boot 应用中配置全局异常处理器,统一处理应用中可能出现的各种异常,提高应用的稳定性和可维护性。在这个方法中,可以根据不同的异常类型返回不同的响应内容,也可以进行日志记录等操作。注解,这个注解表示该类是一个全局的控制器增强类,用于处理控制器中抛出的异常。如果有自定义的异常,可以专门为其创建处理方法。例如,假设存在一个自定义异常。注解来指定要处理的异常类型。 阅读详情

相关推荐

Spring Boot 整合——RabbitMQ配置消息确认回调、消息转换以及消息异常处理

消息回调 消息队列在实际运用中,作为消息的生产者,很多时候我们需要确认消息是否成功发送到了mq中。同时我们还需要知道,假如消息出现异常时的异常情况。为了满足这个业务场景,我们就需要配置消息回调。 开启消息回调 为了保证消息生产者能够收到消息的回调信息,我么需要修改以下配置,只有添加了下面的配置,才能保证添加相关代码后可以收到系统的回复。 spring: rabbitmq: # 开启发送...

大风的博客 1万+

SpringBoot中四种异常处理的方式

SpringBoot 默认的异常处理机制:一旦程序中出现了异常 SpringBoot 就会请求 /error 的 url。在 SpringBoot 中提供了一个叫 BasicExceptionController 来处理 /error 请求,它会跳转到默认显示异常的页面来展示异常信息。不过我们可以在 resources/templates/ 内添加 error 页面来自定义异常页面,名字和路径不能更改,因为BasicExceptionController 默认跳转到这此路径。

yu的博客 1999

SpringBoot处理全局异常详解(全面详细+Gitee源码)

我们对常见的七种异常情况统一进行处理,这次的主角就是@RestControllerAdvice这个注解,这个一个组合注解由@ControllerAdvice和@ResponseBody组成,@RestControllerAdvice会帮助我们把信息转成json格式返回。在全局异常处理类只需要在类上标注@RestControllerAdvice,并在处理相应异常的方法上使用@ExceptionHandler注解,写明处理哪个异常即可。注:异常的拦截有顺序,子类异常会优先匹配子类异常处理器。

黄团团的个人博客 2909

SpringBoot统一异常处理详解

Spring Boot后端接口规范Spring在3.2版本增加了一个注解,可以与、、等注解注解配套使用。不过跟异常处理相关的只有注解,从字面上看,就是异常处理器的意思**Assert(断言)**是Spring 家族的,在我们写测试用例的时候经常会用到,使用断言能让我们编码的时候有一种非一般丝滑的感觉Assert的部分源码,可以看到,Assert 其实就是帮我们把 if {…} 封装了一下,抛出的异常是} } }

Shawn的个人博客 1万+

解决Spring Boot启动异常:未配置数据源的问题

在本文中,我们解决了Spring Boot启动过程中的数据源配置异常问题。我们通过添加数据库依赖并配置正确的数据源信息,成功解决了启动异常。请注意,在实际开发中,你可能需要根据自己的具体情况进行适当的调整和修改。在使用Spring Boot开发Java应用程序时,经常会遇到启动过程中的异常情况。其中一个常见的问题是未配置数据源,导致应用程序无法正常启动。这个异常信息表明在启动应用程序时,Spring Boot无法找到可用的数据源配置。这次应该能成功启动,并且不再出现数据源配置的异常。步骤3:启动应用程序。

TechRoar的博客 1276

Oracle 19c RAC安装踩坑实录:OpenSSH 8.x版本与OUI的“兼容性战争”及一劳永逸的解决思路

本文深入解析Oracle 19c RAC在Linux8环境中部署时遇到的OpenSSH 8.x版本兼容性问题,特别是[INS-06006]错误的根源与解决方案。从协议层分析冲突本质,提供SCP包装器技术、官方补丁应用指南及现代化部署体系构建三种解决方案,帮助企业高效完成RAC安装并规避类似问题。

weixin_42648844的博客 462

SpringBoot异常处理

SpringBoot默认的异常处理机制springboot默认提供了一套处理异常的机制。一旦程序出现了异常,SpringBoot会向/error的url发送请求。在springboot中提供了一个叫BasicErrorController来处理/error请求,然后跳转到默认显示异常的页面来展示异常信息。如果我们需要将所有的异常统一跳转到自定义的错误页面,需要再/**/***自定义异常类,继承RuntimeException。......

Linging_24的博客 4840

Fiddler抓包实战:5分钟搞定微信公众号历史消息接口分析(附完整Python代码)

本文详细介绍了如何使用Fiddler抓包工具逆向分析微信公众号历史消息接口,并提供完整的Python代码实现。从环境准备、动态参数捕获到商业级采集系统架构设计,全面解析了突破官方接口限制的技术方案,帮助开发者高效获取公众号文章数据。

tree8的博客 335

Spring Boot 配置 logback 实现【异常发送邮件提醒】

Spring Boot 学习笔记(三十九):Spring Boot 配置 logback 来实现异常发送邮件功能

扛麻袋的少年的博客 2567

麒麟V10系统下CoreDump文件自动归档与快速定位指南(附coredumpctl实战)

本文详细介绍了在麒麟V10操作系统下,如何利用systemd-coredump机制和coredumpctl工具实现CoreDump文件的自动化管理与高效调试。内容涵盖从系统架构解析、自动化配置策略,到使用coredumpctl进行快速查询、过滤与深度分析的实战指南,旨在帮助运维人员和开发者快速定位系统崩溃的根本原因,提升问题排查效率。

gg901的博客 233

Yolov26 在 Rk3588 上的 Rknn Onnx 部署实践(c++)

本文介绍了YOLOv26在RK3588平台的C++推理部署方案。重点包括:1)扩展Ultralytics导出格式,新增RKNN_ONNX专用导出选项;2)重构Detect Head结构,使其更适合RKNN推理;3)提供C++侧后处理实现建议。该方案保留了Ultralytics训练生态,通过优化模型结构输出,将解码等操作移至C++端,充分发挥Rockchip NPU性能。适用于RK3588/RK356x等平台,需配合rknn-toolkit2使用,为YOLOv26的嵌入式部署提供完整解决方案。

qq_64366203的博客 2189

Spring Boot 错误页配置和全局异常处理

一、错误页配置 1.1 错误页控制器 package com.siniswift.efb.acars.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * 错误页控制器 * * @a...

AaronSimon的博客 1323

Apollo control模块横向控制原理及核心代码逐行解析

看完这篇文章,你会对apollo横向控制有一个整体的概念

weixin_39199083的博客 2万+

Spring Boot 实现邮件发送功能:基于 QQ 邮箱配置与异常通知

在开发中,我们经常需要通过邮件发送通知,例如程序异常、注册验证等。本文将介绍如何使用 **Spring Boot** 配置 **QQ 邮箱** 进行邮件发送,并通过 **全局异常处理** 实现自动邮件通知功能。

haoshenwan的博客 3006

App 抓包难?Frida Hook 实战:绕过 SSL Pinning (证书绑定) 抓取某大厂 App 核心接口

当我们使用 Charles 抓包 HTTPS 时,本质上是实施了MITM(中间人攻击)。Charles 伪装成服务器,发给 App 一个自己的证书(伪造证书)。Charles 伪装成 App,拿着真正的证书去请求服务器。如果 App 只是简单校验“证书是否由受信任的 CA 签发”,那你把 Charles 的根证书安装到手机系统里,就能骗过它。但是,是 App 内置了服务器证书的Hash(指纹)。

BUG猿的博客 937

(四) OpenClaw-Skill技能全面了解和自定义技能

OpenClaw Skills是提升AI代理功能性的关键模块。本文系统介绍了Skills的核心概念、获取渠道和创建方法。Skills作为标准化指令集合,能让OpenClaw从单纯理解升级为实际执行任务,相比传统System Prompt具有模块化、可复用等优势。用户可通过Clawhub官方商店、GitHub社区等渠道获取5700+现成技能,或按需开发自定义Skill。文章详细演示了创建"Hello World"示例技能的完整流程,包括编写Python脚本、配置SKILL.md文件、部署。

直到世界的尽头 8314

spring boot下统一异常处理+log4j日志配置

日志配置:    pom文件导入:&lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter&lt;/artifactId&gt; &lt;exclusions&gt; &lt;exclusion&gt;

zldzs的博客 2154

第 1 篇:对象池模式 (Object Pool) —— 裸机下的动态内存革命

摘要:嵌入式开发中频繁malloc/free会导致内存碎片和性能问题。对象池模式通过预分配固定大小内存块和位图管理,实现O(1)时间复杂度的内存分配/释放。相比malloc,对象池具有无碎片、确定性执行时间、更低内存开销等优势,尤其适合实时系统。文章详细解析了基于位图的对象池实现原理,包括核心数据结构、高性能索引算法和关键API设计,并对比了空间/时间开销,最后讨论了零拷贝队列、调试水印等进阶用法。该模式能显著提升嵌入式系统的内存使用效率和稳定性。

一路往蓝-Anbo 的博客 428

Spring Boot logback异常邮件告警实战配置

日志告警是生产环境故障响应的第一道防线,其核心在于将ERROR级别异常自动识别、上下文富化并实时触达责任人。logback作为Spring Boot默认日志框架,凭借原生异步支持、MDC上下文注入和SMTPAppender聚合能力,可构建低侵入、高可靠的轻量级告警机制。相比Log4j2,它在高并发下更稳定、配置更简洁、故障隔离性更强,特别适合未部署APM的中小系统。本文聚焦logback异常捕获与邮件告警的工程落地,涵盖SMTPAppender配置、cyclicBufferTracker聚合、MDC链路追踪

weixin_30399155的博客 359

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Spring boot 数据源未配置异常

问题 在使Springboot自动生成的项目框架时如果选择了数据源,比如选择了mysql,生成项目之后,启动会报一下异常: Description: Cannot determine embedded database driver class for database type NONE Action: If you want an embedded database please put...

weixin_34352005的博客 276

深度学习工具包 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配置加载异常:InvalidConfigDataPropertyException排查

在Spring Boot应用开发中,配置文件加载机制决定了应用能否正确识别环境与依赖属性。Spring Boot 2.4起引入全新的ConfigData加载体系,将配置来源抽象为结构化数据块,并对profile解析顺序进行了严格限制。当spring.profiles.active或spring.profiles.include出现在通过spring.config.import导入的资源中时,就会触发InvalidConfigDataPropertyException,导致启动失败。这类异常常见于从旧版本升级

weixin_30074763的博客 232

jre9下载 jdk9

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

Spring Boot 配置加载异常:InvalidConfigDataPropertyException 全解析

Spring Boot 2.4 对配置文件加载模型做了重构,引入全新的 Config Data API,将配置文件抽象为 ConfigDataResource,并通过 ConfigDataEnvironmentContributors 统一协调加载。当 spring.profiles.active、spring.profiles.group 等受控属性出现在被导入文件或 profile 专用配置文件中时,框架会抛出 InvalidConfigDataPropertyException,导致项目启动失败。这种

weixin_31188927的博客 137

Spring Boot + MyBatis Plus + Dynamic Datasource 多数据源配置异常

所以这是个“幽灵”报错,我开始意识到我排错方向出现了问题,于是复原了刚刚的所有改动,回到了最初始的报错。我注意到建议行动里有一条**“如果你想要一个嵌入式数据库(H2、HSQL或Derby),请将其放在类路径上”**,我配置的是MySQL而非嵌入式数据库,在我的pom文件里也没有引入嵌入式数据库的依赖,那么为什么它会认为我想要使用嵌入式数据库呢?那为什么我配对了,但它觉得我没配呢?)没有生效,所以Spring Boot默认会退回去尝试使用嵌入式数据库,但发现我没加这些依赖,就报错了。才能激活动态数据源。

oxybabe的代码世界 940

Spring Boot配置异常排查:InvalidConfigDataPropertyException的成因与修复

Spring Boot应用启动时的配置加载机制是微服务工程实践中的基础环节。自2.4版本引入Config Data概念后,配置来源扩展为spring.config.import、外部配置目录等多种形式,这为环境差异化管理和共享配置提供了灵活性。但若在导入的外部配置中出现spring.profiles.active等影响激活状态判断的属性,就会触发InvalidConfigDataPropertyException,导致启动失败。理解配置数据的加载顺序与优先级,是规避此类问题的关键。在实际部署中,通过合理划分

weixin_33290540的博客 281
上一篇: Spring boot 参数校验
下一篇: Spring boot Lombok
xiaoduup
博客等级 码龄9年 23粉丝 83原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址