Java EE 进阶:SpringBoot 配置⽂件

news2025/4/21 20:30:21

什么是配置文件

“配置文件”是一个用来保护程序或者系统设置信息的文件,它的作用是让程序在启动或者运行中,能够读取这些设置并按预期进行工作,而不需要手动的设置。

Spring Boot 配置文件

  • 设置服务器端口、编码格式
  • 配置数据库连接
  • 控制日志级别
  • 设置缓存、邮件、消息队列等服务参数
  • 管理不同环境(开发、测试、生产)下的配置

Spring Boot中的配置文件一共有两种形式

.properties文件 和  .yml  /.yaml文件

properties 基本语法

properties 是以键值的形式配置的,key和value之间是以"="连接的

spring.application.name=spring-ioc demo
server.port=8081


spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root


#自定义
my.key=10
my.key2=true

 

yml基本语法

yml是树形结构的配置⽂件,它的基础语法是"key:value"

记住:在key:value中“ :”后一定要加空格

server:
  port: 8081

my:
  key: 11


spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8&useSSL=false

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/testdb?characterEncoding=utf8&useSSL=false
    username: admin
    password: 123456


#自定义的key
aa.bb.cc=5
aa.bb.dd=6
aa.bb.cc: 5
aa.bb.dd: 6

#字符串
string.value: hello

#布尔值,true/false
boolean.value: false
boolean.value1: true

#整数
int.value: 12

#浮点数
float.value: 12.12


#Null,~代表Null
null.value: ~

  "" 空字符串
empty.value: ''
#里面什么都不用写

yml的配置读取

用@value注解和@ConfigurationProperties注解来读取文件

两个注解的区别:@value注解用于读取单个配置项,@ConfigurationProperties注解用于批量注入多个配置项

@value注解

@Controller
public class YmlController {

    @Value("${my.key3}")
    private String myKey3;

    @Value("${my.key4}")
    private String myKey4;

    @PostConstruct
    public void print(){
        System.out.println(myKey3);
        System.out.println(myKey4);
    }
}
my:
  key3: Hello
  key4: 5

 

@ConfigurationProperties注解

集合和Map的配置

@Data
@ConfigurationProperties(prefix = "dbtypes")
@Component
public class DbTypes {
    private Integer id;
    private List<String> name;
    private Map<String,String> ball;
}

@Data
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private Integer id;
    private String name;
    private Integer age;
}

@Controller
public class YmlController {

   
    @Autowired
    private Person person;

    @Autowired
    private DbTypes dbTypes;

    @PostConstruct
    public void print(){
        System.out.println(person);
        System.out.println(dbTypes);
    }
}

在yml配置文件中

person:
  id: 1
  name: zhangsan
  age: 15

dbtypes:
  id: 4
  name:
    - 123
    - sa
    - ss
  ball:
    k1: v1
    k2: v2
    k3: v3

 

yml的优缺点:

优点

1.结构清晰,一目了然 

 2.支持复杂数据类型(List、Map 等)

3.语法简洁,没有重复前缀

4.可读性强

 

缺点

1.缩进必须正确,容易出错

2.不适合写大量注释

3.调试时不容易发现问题

验证码案例

随着安全性的要求越来越⾼,⽬前项⽬中很多都使⽤了验证码,验证码的形式也是多种多样,更复杂的图 形验证码和⾏为验证码已经成为了更流⾏的趋势。

我们通过Hutool提供的小工具来实现验证码

需求:

在页面上生成验证码图案,然后通过输入验证码图形输入正确的验证码通过验证。

首先我们打开Hutool,找到图形验证码

 

操作流程:

导入包,引入依赖

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.16</version>
        </dependency>

 首先我们先生成验证码

我们生成的是圆圈干扰图形的验证码

 CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(captchaProperties.getWidth(),captchaProperties.getLength());
 String code=captcha.getCode();

由于用户输入完验证码,我们需要对比是否输入正确,所以我们需要得到正确的验证码,所以我们需要在生成验证码后,将正确的验证码存到Session中

     session.setAttribute(captchaProperties.getSession().getKey(),code);
     session.setAttribute(captchaProperties.getSession().getDate(),new Date());
     captcha.write(response.getOutputStream());

然后我们需要进行一个校验 ,判断用户输入的验证码是否正确

if (StringUtil.isNullOrEmpty(captcha)){
            return false;
        }
        String code =(String) session.getAttribute(captchaProperties.getSession().getKey());
        Date date =(Date) session.getAttribute(captchaProperties.getSession().getDate());
        if(captcha.equalsIgnoreCase(code) && date!=null  && System.currentTimeMillis()-date.getTime()<VALID_TIME){
            return true;
        }
        return false;

我们将图形的大小写入配置文件中

captcha:
  width: 150
  length: 100
  session:
    key: CAPTCHA_SESSION_KEY
    date: CAPTCHA_SESSION_DATE

并且用户在输入验证码时有时间限制,超过了一定的时间,就会失效,所以我们需要定义一段时间限制

一分钟

private final static Long VALID_TIME=60*30*1000L;

系统现在的时间 - 输入开始的时间 < 一分钟  

System.currentTimeMillis()-date.getTime()<VALID_TIME

然后在前端代码中写入接口

 $.ajax({
        type:"post",
        url:"/captcha/check",
        data:{
          captcha:$("#inputCaptcha").val()
        },
        success:function(result){
          if(result){
            location.href="success.html";
          }else{
            alert("输入失败,请重新输入");
          }
        }

并且在前段代码中写入

  <meta charset="utf-8">
  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
  <meta http-equiv="Pragma" content="no-cache" />
  <meta http-equiv="Expires" content="0" />

它们用于防止浏览器缓存网页内容,确保每次都从服务器加载最新资源(特别适合验证码、表单、动态页面等场景)。 

演示效果如下:

输入错误的验证码

输入正确的验证码

 

 

后端代码

CaptchaProperties
@Data
@ConfigurationProperties(prefix = "captcha")
@Configuration
public class CaptchaProperties {
    private Integer width;
    private Integer length;
    private Session session;

    @Data
    public static class Session {
        private String key;
        private String date;
    }
}
CaptchaController
package com.blame.springcaptcha.captcahController;

import ch.qos.logback.core.util.StringUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.blame.springcaptcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Date;

@RequestMapping("captcha")
@RestController
public class CaptchaController {

    @Autowired
    private CaptchaProperties captchaProperties;

    private final static Long VALID_TIME=60*30*1000L;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("image/jpeg");
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(captchaProperties.getWidth(),captchaProperties.getLength());
        String code=captcha.getCode();
        session.setAttribute(captchaProperties.getSession().getKey(),code);
        session.setAttribute(captchaProperties.getSession().getDate(),new Date());
        captcha.write(response.getOutputStream());

    }

    @RequestMapping("/check")
    public boolean check(HttpSession session,String captcha){
        if (StringUtil.isNullOrEmpty(captcha)){
            return false;
        }
        String code =(String) session.getAttribute(captchaProperties.getSession().getKey());
        Date date =(Date) session.getAttribute(captchaProperties.getSession().getDate());
        if(captcha.equalsIgnoreCase(code) && date!=null  && System.currentTimeMillis()-date.getTime()<VALID_TIME){
            return true;
        }
        return false;
    }

}

.yml文件

spring:
  application:
    name: Spring-captcha

captcha:
  width: 150
  length: 100
  session:
    key: CAPTCHA_SESSION_KEY
    date: CAPTCHA_SESSION_DATE

 

 前端代码

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
  <meta http-equiv="Pragma" content="no-cache" />
  <meta http-equiv="Expires" content="0" />

  <title>验证码</title>
  <style>
    #inputCaptcha {
      height: 30px;
      vertical-align: middle; 
    }
    #verificationCodeImg{
      vertical-align: middle; 
    }
    #checkCaptcha{
      height: 40px;
      width: 100px;
    }
  </style>
</head>

<body>
  <h1>输入验证码</h1>
  <div id="confirm">
    <input type="text" name="inputCaptcha" id="inputCaptcha">
    <img id="verificationCodeImg" src="/captcha/getCaptcha" style="cursor: pointer;" title="看不清?换一张" />
    <input type="button" value="提交" id="checkCaptcha">
  </div>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
  <script>
    
    $("#verificationCodeImg").click(function(){
      $(this).hide().attr('src', '/captcha/getCaptcha?dt=' + new Date().getTime()).fadeIn();
    });

    
    $("#checkCaptcha").click(function () {
        
      $.ajax({
        type:"post",
        url:"/captcha/check",
        data:{
          captcha:$("#inputCaptcha").val()
        },
        success:function(result){
          if(result){
            location.href="success.html";
          }else{
            alert("输入失败,请重新输入");
          }
        }

      })
    });

  </script>
</body>

</html>

success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>验证成功页</title>
</head>
<body>
    <h1>验证成功</h1>
</body>
</html>

 

希望能对大家有所帮助!!!!

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2314618.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【redis】五种数据类型和编码方式

文章目录 五种数据类型编码方式stringhashlistsetzset查询内部编码 五种数据类型 字符串&#xff1a;Java 中的 String哈希&#xff1a;Java 中的 HashMap列表&#xff1a;Java 中的 List集合&#xff1a;Java 中的 Set有序集合&#xff1a;除了存 member 之外&#xff0c;还有…

色板在数据可视化中的创新应用

色板在数据可视化中的创新应用&#xff1a;基于色彩感知理论的优化实践 引言 在数据可视化领域&#xff0c;色彩编码系统的设计已成为决定信息传递效能的核心要素。根据《Nature》期刊2024年发布的视觉认知研究&#xff0c;人类大脑对色彩的识别速度比形状快40%&#xff0c;色…

【无人机路径规划】基于麻雀搜索算法(SSA)的无人机路径规划(Matlab)

效果一览 代码获取私信博主基于麻雀搜索算法&#xff08;SSA&#xff09;的无人机路径规划&#xff08;Matlab&#xff09; 一、算法背景与核心思想 麻雀搜索算法&#xff08;Sparrow Search Algorithm, SSA&#xff09;是一种受麻雀群体觅食行为启发的元启发式算法&#xff0…

STM32_GPIO系统外设学习

按照STM32MCUWIKI、参考手册的外设介绍----->CubeF4的软件包中相关的Exmple代码----->CubeMX设置截图加深理解记忆 资料链接&#xff1a;嵌入式开发_硬软件的环境搭建 我的飞书文档-GPIO篇 如果觉得内容不错&#xff0c;欢迎给我的飞书文档点赞。同时如果有什么意见或…

【操作系统安全】任务1:操作系统部署

目录 一、VMware Workstation Pro 17 部署 二、VMware Workstation 联网方式 三、VMware 虚拟机安装流程 四、操作系统介绍 五、Kali 操作系统安装 六、Windows 系统安装 七、Windows 系统网络配置 八、Linux 网络配置 CSDN 原创主页&#xff1a;不羁https://blog.csd…

下载安装启动 VMware 个人免费版本

一、进入官网并登录账号下载软件 进入官网 [ https://www.vmware.com ]&#xff0c;点击Products&#xff0c;将页面划到最底下&#xff0c;点击 “SEE DESKTOP HYPERVISORS”按钮。 然后点击 Desktop hypevisor &#xff0c;会出现如下界面&#xff0c;可以根据自己的操作系…

C#+AForge 实现视频录制

C#AForge 实现视频录制 ​ 在C#中&#xff0c;使用AForge 库实现视频录制功能是一个比较直接的过程。AForge 是一个开源的.NET框架&#xff0c;提供了许多用于处理图像和视频的类库。 开发步骤 安装AForge库 ​ 首先&#xff0c;确保你的项目中已经安装了 AForge.Video和AFo…

SAP SD学习笔记31 - 销售BOM

上一篇讲 前受金处理(预付款处理)。 SAP SD学习笔记29 - 前受金处理(预收款处理)_fplt 付款申请与sd 数据表的关联关系-CSDN博客 本章继续讲SAP SD模块的其他知识&#xff1a;销售BOM。 销售BOM在现场还是会用到的。 目录 1&#xff0c;销售BOM概要 2&#xff0c;受注BOM的…

大数据学习(63)- Zookeeper详解

&&大数据学习&& &#x1f525;系列专栏&#xff1a; &#x1f451;哲学语录: 用力所能及&#xff0c;改变世界。 &#x1f496;如果觉得博主的文章还不错的话&#xff0c;请点赞&#x1f44d;收藏⭐️留言&#x1f4dd;支持一下博主哦&#x1f91e; &#x1f…

嵌入式八股C语言---面向对象篇

面向对象与面向过程 面向过程 就是把整个业务逻辑分成多个步骤,每步或每一个功能都可以使用一个函数来实现面向对象 对象是类的实例化,此时一个类就内部有属性和相应的方法 封装 在C语言里实现封装就是实现一个结构体,里面包括的成员变量和函数指针,然后在构造函数中,为结构体…

C# ListView设置标题头背景颜色和字体颜色

一、向ListView 添加数据 for (int i 1; i < 5; i) {ListViewItem litem new ListViewItem("data:"i);lv_WarnList.Items.Add(litem); }如果需要在ListView中绑定实体类对象的话&#xff0c;需要将数据放在Tag属性里 for (int i 1; i < 5; i) {AngleData …

嵌入式 ARM Linux 系统构成(6):应用层(Application Layer)

目录 一、应用层概述 二、应用层的核心组成 2.1 主应用程序&#xff08;Main Applications&#xff09; 2.2 系统服务&#xff08;System Services&#xff09; 2.3 用户界面&#xff08;User Interface&#xff09; 2.4 脚本与自动化工具 2.5 第三方库与框架 2.6 通信…

【HTML】一、基础标签

文章目录 1、开发环境准备2、html介绍3、html基本骨架4、标签的关系5、常用标签5.1 标题5.2 段落5.3 换行与水平线5.4 文本格式化标签5.5 图像标签5.6 超链接标签5.7 音频标签5.8 视频标签 6、路径7、网页制作 1、开发环境准备 在编辑器中写代码&#xff0c;在浏览器中看效果 …

centos7通过yum安装redis

centos7通过yum安装redis 1.安装redis数据库 yum install -y redis2.启动redis服务 systemctl start redis3.查看redis状态 systemctl status redis4、停止服务 systemctl stop redis5、重启服务 systemctl restart redis6、查看redis进程 ps -ef | grep redis7、开放端…

AutoMQ x OSS 的 Iceberg 数据入湖的最佳实践

背景 在数字化转型进程中&#xff0c;用户交互行为产生的多维度数据已成为企业的重要战略资产。以短视频平台为例&#xff0c;基于用户点赞事件的实时推荐算法能显著提升用户活跃度和平台粘性。这类实时数据主要通过 Apache Kafka 流处理平台进行传输&#xff0c;通过其扇出&a…

【Help Manual】导出PDF中英文不在一行解决方案

在使用Help Manual 的时候&#xff0c;会出现导出PDF时&#xff0c;中英文在同一行出现水平不对齐的问题。如下&#xff1a; 解决方案&#xff1a; 结果如下&#xff1a;

Scala编程_实现Rational的基本操作

在Scala中实现一个简单的有理数&#xff08;Rational&#xff09;类&#xff0c;并对其进行加法、比较等基本操作. 有理数的定义 有理数是可以表示为两个整数的比值的数&#xff0c;通常形式为 n / d&#xff0c;其中 n 是分子&#xff0c;d 是分母。为了确保我们的有理数始终…

用python和Pygame库实现“跳过障碍”游戏

用python和Pygame库实现“跳过障碍”游戏 游戏开发 跳过障碍游戏流程说明&#xff1a; 启动游戏后显示开始界面&#xff08;包含游戏说明&#xff09; 按空格键进入游戏 游戏过程中躲避障碍物获取分数 碰撞后显示结束界面&#xff08;包含最终得分&#xff09; 按空格键…

SqlServer数据库报错紧急或可疑无法访问的修复过程,亲测有效。

当 SQL Server 数据库被标记为 SUSPECT 状态时&#xff0c;表示数据库可能由于事务日志损坏、数据文件丢失或其他严重问题而无法正常启动。以下是一个详细的恢复步骤&#xff0c;基于搜索结果中的信息和常见的最佳实践&#xff1a; 恢复步骤 1. 确认数据库状态 将database-n…

【python-uiautomator2】手机上的ATX应用界面报错问题处理:无法提供服务,非am instrument启动

目录 一、前期准备 1.1 插入设备 1.2 安装atx-agent 二、解决报错&#xff1a;无法提供服务&#xff0c;非am instrument启动 2.1 出现报错 2.2 尝试解决 2.3 最终解决 三、开启ATX的悬浮窗权限 一、前期准备 1.1 插入设备 本地插入待执行设备&#xff0c;待执行设备…