SpringBoot Starter,自定义全局加解密组件

使用国密SM2算法报错 没有添加Bouncy Castle算法提供者。添加Bouncy Castle算法提供者。 阅读详情

👉 这是一个或许对你有用的社群

🐱 一对一交流/面试小册/简历优化/求职解惑,欢迎加入「芋道快速开发平台」知识星球。下面是星球提供的部分资料: 

f72c604c79ecd5217b685b7f7c4be6c5.gif

👉这是一个或许对你有用的开源项目

国产 Star 破 10w+ 的开源项目,前端包括管理后台 + 微信小程序,后端支持单体和微服务架构。

功能涵盖 RBAC 权限、SaaS 多租户、数据权限、商城、支付、工作流、大屏报表、微信公众号、CRM 等等功能:

  • Boot 仓库:https://gitee.com/zhijiantianya/ruoyi-vue-pro

  • Cloud 仓库:https://gitee.com/zhijiantianya/yudao-cloud

  • 视频教程:https://doc.iocoder.cn

【国内首批】支持 JDK 21 + SpringBoot 3.2.2、JDK 8 + Spring Boot 2.7.18 双版本 

来源:www.cnblogs.com/
xbhog/p/18012435

718a0cec278893abf29b1e9c9dab49f4.jpeg


目的

  • 了解SpringBoot Starter相关概念以及开发流程

  • 实现自定义SpringBoot Starter(全局加解密)

  • 了解测试流程

  • 优化

最终引用的效果:

<dependency>
    <groupId>com.xbhog</groupId>
    <artifactId>globalValidation-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

开源地址

https://gitee.com/xbhog/encry-adecry-spring-boot-starter

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/ruoyi-vue-pro

  • 视频教程:https://doc.iocoder.cn/video/

了解SpringBoot Starter相关概念以及开发流程

SpringBoot Starter

SpringBoot Starter作用将一组相关的依赖打包,简化项目的配置和初始化过程,通过特定的Starter开发者可以快速的实现特定功能模块的开发和扩展。

自定义Starter能够促进团队内部资源的复用,保持项目间的一致性,提升协作效率并且有助于构建稳定、高效的大型系统。

开发流程

注入SpringBoot的方式

在刚开始开发Starter的时候,首先考虑的是怎么能注入到SpringBoot中?

这部分涉及到部分SpringBoot的自动装配原理,不太清楚的朋友可以补习下;

注入SpringBoot需要配置文件,在项目中的resources资源目录中创建该目录和文件。

demo-spring-boot-starter
└── src
    └── main
        └── java
            └── com.xbhog
                ├── DemoBean.java
                └── DemoBeanConfig.java
        └── resources
                └── META-INF
                    └── spring.factories

在spring.factories中我们指定一下自动装配的配置类,格式如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.xbhog.DemoBeanConfig
@Slf4j
@Configuration
public class DemoBeanConfig {

    @Bean
    public DemoBean getDemo() {
        log.info("已经触发了配置类,正在初始化DemoBean...");
        return new DemoBean();
    }
}
@Slf4j
public class DemoBean {
    public void getDemo(){
      log.info("方法调用成功");
    }
}

这样就可以将设置的包扫描路径下的相关操作打包到SpringBoot 中。

SpringBoot主类启动器:初始化的操作,感兴趣的朋友可以研究下

a3a48c5ea87c77b91882cb9d320a9a8d.png 41487a61839ce16058ec2d3495c25b1b.png

完成后,我们可以打包该项目,然后在测试工程红进行Maven的引入、测试。

测试

新建Spring 测试工程,引入依赖:

<dependency>
    <groupId>com.xbhog</groupId>
    <artifactId>demo-spring-boot-starter</artifactId>
    <version>1.0</version>
</dependency>
@RestController
public class BasicController implements ApplicationContextAware {
    private ApplicationContext applicationContext;
    
    /**两种引入方式都可以
    @Autowired
    private DemoBean demoBean;*/

    @GetMapping("/configTest")
    public void configTest() {
        DemoBean demoBean = applicationContext.getBean(DemoBean.class);
        demoBean.getDemo();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

请求地址后,可以观察控制台,如下日志表示SpringBoot Starter可以使用了。

e1d23b93a63116151579d8c1aa27006e.png

到此,一个简单的Starter开发完成了,后续可以围绕工程,根据需求和业务,对通用功能(接口操作日志、异常、加解密、白名单等)进行封装,最后打到Maven仓库中进行使用。

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/yudao-cloud

  • 视频教程:https://doc.iocoder.cn/video/

自定义SpringBoot Starter(全局加解密)

来源

在之前金融系统开发中,需要对接多个第三方的服务且数据安全性要求比较高;在接口评审阶段需要双方在数据传输的时候进行接口加解密;起初在第一个服务对接的时候,将相关的加解密操作写到工具类中;随着后续服务的增多,代码的侵入越来越严重。

封装

选择通过Starter进行功能的封装;好处:引用方便,开发迭代方便,团队复用度高且对业务没有侵入。

开发

思路:通过配置文件初始化,让配置类注解@ComponentScan扫描到的Bean等注入到SpringBoot中,通过自定义注解和RequestBodyAdvice/ResponseBodyAdvice组合拦截请求,在BeforBodyRead/beforeBodyWrite中进行数据的前置处理,解密后映射到接口接收的字段或对象。

接口上的操作有两种方式:

  • 注解+AOP实现

  • 注解+RequestBodyAdvice/ResponseBodyAdvice

这里我选择的第二种的RequestBodyAdvice/ResponseBodyAdvice,抛砖引玉一下。

【注】第二种存在的局限性是:只能针对POST请求中的Body数据处理,无法针对GET请求进行处理。

项目结构:

encryAdecry-spring-boot-starter
└── src
    └── main
        └── java
            └── com.xbhog
                ├── advice
                │   ├──ResponseBodyEncryptAdvice.java
                │   └──RequestBodyDecryptAdvice.java
                ├── annotation
                │   └──SecuritySupport
                ├── handler
                │    ├──impl
                │    │   └──SecurityHandlerImpl.java
                │    └──SecurityHandler
                └── holder
                │    ├──ContextHolder.java
                │    ├──EncryAdecryHolder.java
                │    └──SpringContextHolder.java
                └──GlobalConfig.java
        └── resources
                └── META-INF
                    └── spring.factories

项目处理流程图:

3d3d346810667f684036cbf9efb9d66a.png

核心代码:

@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
    log.info("进入【RequestBodyDecryptAdvice】beforeBodyRead的操作,方法:{}",parameter.getMethod());
    SecuritySupport securitySupport = parameter.getMethodAnnotation(SecuritySupport.class);
    assert securitySupport != null;
    ContextHolder.setCryptHolder(securitySupport.securityHandler());
    String original = IOUtils.toString(inputMessage.getBody(), Charset.defaultCharset());
    //todo
    log.info("该流水已插入当前请求流水表");
    String handler = securitySupport.securityHandler();
    String plainText = original;
    if(StringUtils.isNotBlank(handler)){
        SecurityHandler securityHandler = SpringContextHolder.getBean(handler, SecurityHandler.class);
        plainText = securityHandler.decrypt(original);
    }
    return new MappingJacksonInputMessage(IOUtils.toInputStream(plainText, Charset.defaultCharset()), inputMessage.getHeaders());
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    log.info("进入【ResponseBodyEncryptAdvice】beforeBodyWrite的操作,方法:{}",returnType.getMethod());
    String cryptHandler = ContextHolder.getCryptHandler();
    SecurityHandler securityHandler = SpringContextHolder.getBean(cryptHandler, SecurityHandler.class);
    assert body != null;
    return securityHandler.encrypt(body.toString());
}

该Starter中的全局加解密默认采用的国密非对称加密SM2,在开发过程中遇到了该问题InvalidCipherTextException: invalid cipher text

【原因】 私钥和公钥值不是成对存在的,每次调用SmUtil.sm2()会生成不同的随机密钥对。

【解决】在该Starter中采用@PostConstruct修饰方法,在项目运行中只会初始化运行一次该方法,保证了SmUtil.sm2()只会调用一次,不会生成不同的随机秘钥对。

【ISSUES#1890】详细请看该地址:https://hub.fgit.cf/dromara/hutool/issues/1890

@Slf4j
@Component
public class EncryAdecryHolder {
    public static SM2 sm2 = null;
    @PostConstruct
    public void encryHolder(){
        KeyPair pair = SecureUtil.generateKeyPair("SM2");
        byte[] privateKey = pair.getPrivate().getEncoded();
        byte[] publicKey = pair.getPublic().getEncoded();
        log.info("生成的公钥:{}",publicKey);
        log.info("生成的私钥:{}",privateKey);
        sm2= SmUtil.sm2(privateKey, publicKey);
    }
}

除了默认的加密方式,还可以通过SecurityHandler接口进行扩展,扩展出来的impl可以在@SecuritySupport(securityHandler="xxxxxx")中指定。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SecuritySupport {
    /*securityHandlerImpl*/
    String securityHandler() default "securityHandlerImpl";

    String exceptionResponse() default "";

}
测试

复用之前的测试项目,引用打包的mavne依赖:

<dependency>
    <groupId>com.xbhog</groupId>
    <artifactId>encryAdecry-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

启动项目,初始化公私钥。

b3a545db2752169e1671784deb9f15ee.png 3630461041de77a60cecf5003319ffab.png

测试接口代码如下:

@Slf4j
@RestController
public class BasicController implements ApplicationContextAware {
    @Resource(name = "demoSecurityHandlerImpl")
    private SecurityHandler encryAdecry;
    private ApplicationContext applicationContext;

    // http://127.0.0.1:8080/hello?name=lisi
    //@SecuritySupport(securityHandler = "demoSecurityHandlerImpl")
    @SecuritySupport
    @PostMapping("/hello")
    public String hello(@RequestBody String name) {
        return "Hello " + name;
    }

    @GetMapping("/configTest")
    public String configTest(@RequestParam("name") String name) {
        /*DemoBean demoBean = applicationContext.getBean(DemoBean.class);
        demoBean.getDemo();*/
        return encryAdecry.encrypt(name);
        //return MD5.create().digestHex16(name);
    }
}
230458b4129c73badf1968f4cd857042.png
优化

优化后的项目结构:

encryAdecry-spring-boot-starter
└── src
    └── main
        └── java
            └── com.xbhog
                ├── advice
                │   ├──ResponseBodyEncryptAdvice.java
                │   └──RequestBodyDecryptAdvice.java
                ├── annotation
                │   └──SecuritySupport
                ├── handler
                │    ├──impl
                │    │   └──EncryAdecryImpl.java
                │    └──SecurityHandler
                └── holder
                │    ├──ContextHolder.java
                │    └──SpringContextHolder.java
                ├──GlobalProperties.java
                └──GlobalConfig.java
        └── resources
                └── META-INF
                    └── spring.factories

增加配置类,用于绑定外部配置(properties和YAML)到Java对象的的一种机制;

@Data
@ConfigurationProperties(GlobalProperties.PREFIX)
public class GlobalProperties {
    /**
     * 默认前缀
     */
    public static final String PREFIX = "encryption.type";
    /**
     * 加解密算法
     */
    private String algorithmType;

    /**
     * 加解密key值
     */
    private String key;
}

注解修改:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SecuritySupport {
    /**
     * 项目默认加解密实现类encryAdecryImpl
     * */
    String securityHandler() default "encryAdecryImpl";

}

重写Starter默认的加解密方式:

@Slf4j
@Component
public class EncryAdecryImpl implements SecurityHandler {

    @Resource
    private GlobalProperties globalProperties;
    private static volatile SM2 sm2;

    @Override
    public String encrypt(String original) {
        log.info("【starter】具体加密的数据{}",original);
        return sm2.encryptBase64(original, KeyType.PublicKey);
    }

    @Override
    public String decrypt(String original) {
        String decryptData = StrUtil.utf8Str(sm2.decryptStr(original, KeyType.PrivateKey));
        log.info("【starter】具体解密的数据:{}",decryptData);
        return decryptData;
    }

    @PostConstruct
    @Override
    public void init() {
        log.info("======>获取映射的加密算法类型:{}",globalProperties.getAlgorithmType());
        //传的是加密算法
        KeyPair pair = SecureUtil.generateKeyPair(globalProperties.getAlgorithmType());
        byte[] privateKey = pair.getPrivate().getEncoded();
        byte[] publicKey = pair.getPublic().getEncoded();
        sm2= SmUtil.sm2(privateKey, publicKey);
    }
}

欢迎加入我的知识星球,全面提升技术能力。

👉 加入方式,“长按”或“扫描”下方二维码噢:

011ee271d90d4fb7598eb47f2aefafe2.png

星球的内容包括:项目实战、面试招聘、源码解析、学习路线。

2b2abe8cea8d24ce35c728e38aae0a7c.png

763a85cd7da2256e33652f29a81a6977.pnga2b203e0a13f45460327760615414436.png08d2ede6a550a8ba30375b833c5c4c1f.pnga7f665d24395c3c78ee6385fd5663513.png

文章有帮助的话,在看,转发吧。
谢谢支持哟 (*^__^*)
spring-boot-starter-crypt:SpringBoot请求统一加解密 spring-boot-starter-crypt SpringBoot请求统一加解密 使用aes对称加密方式对于传输报文data进行整体加解密 使用rsa对aes 的加密key进行加密 ras公私钥动态获取:在客户端每次启动重新获取公私钥 立即下载

相关推荐

ctf——writeup

ctf线上赛——第三关地址:http://106.75.86.18:2222提示:ip spoofing——ip伪造首先访问目标地址,一个正常的网页,挺文艺的。上面有些提示。根据上面的提示,我们浏览网页。找了好久,终于找到你。这个跳转链接。(在这个页面下方)我们接着点击这个链接,就跳转到administrator.php这个页面了。看到这个登录页面,就要知道用户名,密码,可是没有怎么办。一开始也试

Child_by_dream的博客 1321

Springboot 框架中加解密字段后存储数据库

AesSupport.java 加密解密算法------------------------------------------在业务逻辑中,调用加密服务对需要加密的数据进行加密,并在需要时进行解密。在数据库实体类中,将需要加密的字段定义为加密前的原始字段。定义接口文件--------------------------------------------------//如果判断结果为真,则取出字段属性值,进行加密、重新赋值。//按参数的类型进行判断,如果业务中还有其他的类型,可酌情增加。

石船龙 659

多模态特征融合方法总结

由于本人的研究是文本、语音和图像三者模态数据的融合,所以针对的是这三种模态的特征融合方法进行总结。 首先,多模态特征融合的方法大体分为三种

华辰烟雨的博客 9万+

使用dynamic-datasource-spring-boot-starter自定义数据库密码

使用dynamic-datasource-spring-boot-starter自定义数据库密码

Shiyxu的博客 1600

ArcGIS小白必看:5分钟搞定WGS_1984到Krasovsky_1940_Albers投影转换(附详细步骤)

本文为ArcGIS初学者提供了从WGS_1984地理坐标系转换到Krasovsky_1940_Albers投影坐标系的详细实战指南。文章深入剖析了投影变换与基准面转换的核心区别,通过分步详解创建自定义地理变换、执行投影等关键操作,并附带了常见问题排查与批量处理脚本,旨在帮助用户高效、准确地完成坐标系统转换,为后续空间分析奠定基础。

weixin_29305337的博客 643

保姆级避坑指南:在Ubuntu 22.04上用ROS2 Humble搞定TurtleBot3的SLAM与导航(附5个常见报错解决方案)

本文提供了一份详细的Ubuntu 22.04上使用ROS2 Humble和TurtleBot3进行SLAM建图与导航的避坑指南,涵盖Gazebo启动失败、场景加载问题、环境变量设置、GLIBCXX版本冲突及Nav2参数配置等5个常见报错的解决方案,帮助开发者高效完成机器人导航项目。

weixin_29062823的博客 286

JAVA面试题分享五百六十六:SpringBoot Starter,自定义全局加解密组件

在之前金融系统开发中,需要对接多个第三方的服务且数据安全性要求比较高;在接口评审阶段需要双方在数据传输的时候进行接口加解密;起初在第一个服务对接的时候,将相关的加解密操作写到工具类中;随着后续服务的增多,代码的侵入越来越严重。

之乎者也·的博客 1784

Android软键盘系统深度解析:架构、原理与实现

Android软键盘系统深度解析:架构与实现原理 本文系统剖析了Android软键盘的核心工作机制。作为系统级输入服务,软键盘具有双重属性:既是可安装的独立应用,又深度集成于系统框架中。文章详细解读了软键盘的系统架构,包括其与InputMethodManagerService(IMMS)和WindowManagerService(WMS)的交互机制,以及通过InputConnection实现的跨进程通信流程。同时分析了输入法窗口的特殊管理策略、布局调整模式,并深入探讨了输入预测引擎的实现原理,包括词典加载、

保持专注,保持热爱 117

【SpringBootStarter】自定义全局加解密组件

SpringBoot Starter作用将一组相关的依赖打包,简化项目的配置和初始化过程,通过特定的`Starter`开发者可以快速的实现特定功能模块的开发和扩展。

在长期主义之路上,与伟大格局观者同行,做时间的朋友。 1025

TC3XX - MCAL知识点(二十七):SENT Mcal配置及代码实战(单边半字节传输协议)

SENT协议只有一根线,异步传输!Sent协议的全称为Single Edge Nibble Trans .isson,单边半字节传输协议,是一种单线异步串行通信协议。Sent报文包含8个Nibble和一个校准位如图1所示,每一个Nibble数据被编码成PWM方式。设计这种协议的目的是用在与汽车ECU快速交互信息的传感器上,以此来取代低精确度的10bit AD和PWM。Sent是一种点对点的单方向从传感器到控制端的协议,控制器不需要同步信号。

梦想技术家 2273

【人工智能之深度学习】18. 金融风控实战:TCN时序卷积网络构建信用卡欺诈实时检测系统

摘要:信用卡欺诈交易识别是金融风控的核心环节,其面临欺诈样本占比低(仅0.1%)、实时响应要求高(毫秒级)等挑战。本文基于IEEE-CIS公开数据集,构建基于时序卷积网络(TCN)的欺诈检测系统,通过捕捉用户交易行为的时序模式识别异常。详细阐述全流程:从数据预处理(构造交易序列特征)、TCN模型设计(轻量级架构适配实时场景),到实时检测部署(异步处理确保低延迟)。实验显示,该系统精确率达63%、召回率89%,误杀率仅0.2%,推理延迟8ms,较XGBoost等传统模型性能显著提升。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 1138

Spring Boot 4 集成:@AiService、多模型路由与多租户隔离

Spring Boot 4.1.x 与 LangChain4j 1.23.0 集成需规避多租户数据串扰、模型路由僵化与降级缺失三大陷阱。推荐采用“配置→路由→隔离→降级”四层架构,优先手动 @Bean 确保可控性。通过可配置的多模型路由策略(按场景、租户、成本、健康度)实现精准调度,并结合 Resilience4j 实现熔断与降级,辅以可观测性设计,保障系统稳定性与可维护性。

weixin_43128865的博客 396

手把手教你学Simulink——基于Simulink的无迹卡尔曼滤波(UKF)控制仿真建模示例

本文详细介绍了在Simulink中实现无迹卡尔曼滤波(UKF)控制倒立单摆系统的完整过程。通过对比扩展卡尔曼滤波(EKF),重点阐述了UKF在处理强非线性系统时的优势:采用无迹变换(UT)通过确定性采样捕捉非线性特性,精度可达三阶泰勒展开且无需计算雅可比矩阵。文章分步骤讲解了状态空间定义、UKF参数设计、Simulink实现方法,以及结合LQR控制器的闭环系统搭建,并通过仿真验证UKF在大角度偏移情况下具有更优的估计精度和控制性能。最后还讨论了工程实践要点和扩展方向,为非线性系统控制提供了实用解决方案。

MHD0815的博客 97

spring boot 4集成SQLLite,及其SQLLite的建库

spring boot 4集成SQLLite,及其SQLLite的建库

weixin_41463944的博客 239

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

ZeusSpring框架深度解析:基于Spring Boot的高效模块化企业级开发解决方案与实战指南

1.1 项目背景与定位在现代企业级应用开发中,如何在保证代码质量的同时提升开发效率,是每一个技术团队面临的核心挑战。ZeusSpring正是为了解决这一痛点而生。这是一个由开发者AichaelLee创建并维护的,基于Spring Boot生态的高度可扩展、模块化的开发框架。它并非简单的代码堆砌,而是对Spring Boot进行了深度的增强与封装,旨在为开发者提供一套“开箱即用”且架构清晰的基础设施。1.2 核心价值主张ZeusSpring的核心设计理念在于“模块化”与“高效”。

wulechun的博客 203

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

Spring Boot 和 Spring Cloud 是什么关系

Spring Boot 与 Spring Cloud 是协同关系,非替代或升级。Boot 负责单个服务的快速启动与配置,Cloud 则解决多服务间的注册发现、调用、容错等分布式问题。两者能力不重叠:Boot 管进程内,Cloud 管进程间。Cloud 组件基于 Boot 的自动配置机制实现,依赖版本严格匹配,不可随意升级。是否使用 Cloud,取决于是否有跨服务治理需求,而非项目规模。小系统或已用 K8s 可无需引入完整 Cloud。

2401_89855466的博客 246

深度学习工具包 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 3.x 多模型统一接入实战:Spring AI 1.x 与 LangChain4j 选型对比

多模型统一接入层的本质,是把"模型"从一个 SDK 依赖变成一个可配置、可路由、可降级的运行时依赖。版本对齐是前提,Spring AI 2.0.x 与 Spring Boot 3.x 不共存,别照抄跨路线的依赖;协议兼容是杠杆,但"OpenAI 兼容"必须逐家核对,差异要显式管理而不是假装不存在;抽象层决定演进上限,接入层做对了,RAG、MCP、Agent 编排才是在其上叠加能力,而不是推倒重来。

m0_74899094的博客 324

Java在线租房系统源码解析:Spring Boot+Vue 3+UniApp房源管理与预约看房方案

本文介绍一套基于Java、Spring Boot、Vue 3与UniApp的在线租房平台源码,涵盖租客端、房东端及管理后台三大模块,实现房源展示、在线咨询、预约看房、合同管理与审核治理等核心功能。技术架构清晰,支持多端部署,适用于区域租房平台、公寓运营及定制化开发项目。强调业务流程闭环与数据一致性,提供二次开发指导与验收标准,助力企业快速搭建自有品牌租房系统。

weixin_42648890的博客 232

Spring Boot 系统监控与可观测性

基础的 JVM 和 HTTP 指标看不出来 Outbox 是否出问题,所以 Study 服务里添加,通过Micrometer Gauge + 定时 SQL 统计监控事件状态。status状态含义0PENDING等待发送1SENDING已被某个发布器领取2SENTBroker 已确认并通过路由检查3FAILED达到最大重试次数,待人工处理",其他SENDING、`FAILED` 指标同理;实际代码里需要异常处理,避免指标采集影响业务调度。Gauge。

m0_64642997的博客 358

ChatGPT、Codex并发排查:Spring Boot接口没有报错,为什么线程池队列越来越长,最后整批请求超时?

Spring Boot接口没有报错,CPU和数据库连接池也正常,为什么线程池队列却越来越长?本文从订单服务任务积压故障切入,分析无界队列、最大线程数、CallerRunsPolicy、下游阻塞和任务背压机制,并介绍通过Codex辅助定位线程池瓶颈的方法。

2601_96380027的博客 225

Java加油团油系统源码解析:Spring Boot+UniApp实现油站管理、加油支付与商家结算

本文介绍一套基于Java、Spring Boot、UniApp与Vue 3的加油团油系统,涵盖用户端找油站支付、商家端核验结算、平台后台管理三大模块。系统实现优惠支付、订单核验、多端协同与二次开发接口,适用于油站线上化、区域合作及会员运营场景,助力企业高效开展多站点运营管理。

weixin_42648890的博客 189

Spring Boot 升到 2.6 启动报错,循环依赖为何被默认禁掉

升到 Spring Boot 2.6 后,字段注入的循环依赖被默认禁掉,服务一启动就抛异常退出。排查按四步走,从异常类名一路定位到互相引用的字段代码。

昨日种种,皆成今我。今日种种,皆成新我。 283

ChatGPT、Codex工程实战:Kubernetes滚动发布时,Spring Boot正在处理的请求为什么还是会被中断?

本文从Java订单系统生产故障切入,分析Readiness Probe、EndpointSlice、preStop、SIGTERM、Tomcat优雅停机和terminationGracePeriodSeconds之间的关系,并介绍通过Codex还原Pod终止时间线、排查502和Connection reset的方法。

2601_96380027的博客 521

《基于Spring Boot的迷游哈游戏综合服务平台的开发》

本文设计并实现了一款基于SpringBoot的“迷游哈”游戏综合服务平台,解决玩家攻略分享与二手交易分散、信息杂乱、交易无保障等问题。系统采用B/S架构,支持普通用户、服务人员、管理员三类角色,具备攻略投稿审核、商品交易闭环、余额充值提现、在线客服与投诉工单处理等核心功能,实现内容共建、资金流转、售后保障等多维度业务闭环。技术栈主流(Java+Vue3+MySQL),模块清晰,开发难度适中,覆盖后端开发、数据库设计等核心知识点,兼具实用性与教学价值,适合作为本科毕业设计选题。

407
上一篇: 2个令人惊艳的开源项目,诞生了!
下一篇: 微信聊天内容可以被监听吗
公众号-芋道源码
博客等级 码龄10年 1639粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值