当前位置 博文首页 > 文章内容

    layman的博客:SpringBoot中注解@ConfigurationProperties的作用

    作者:shunshunshun18 栏目:未分类 时间:2021-10-27 20:28:16

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    作用

    @ConfigurationProperties的作用:可以读取配置文件中的信息,并自动封装成实体类,该实体类的名称,默认是类名的首字母小写。

    比如,在application.yml中有这样的内容:

    # 安全配置
    security:
      # 验证码
      captcha:
        enabled: true
        type: math
    

    代码演示

    package com.ruoyi.gateway.config.properties;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.cloud.context.config.annotation.RefreshScope;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * 验证码配置
     */
    @Configuration
    @RefreshScope
    @ConfigurationProperties(prefix = "security.captcha")
    public class CaptchaProperties{
        /**
         * 验证码开关
         */
        private Boolean enabled;
        /**
         * 验证码类型(math 数组计算 char 字符)
         */
        private String type;
    
        public Boolean getEnabled(){
            return enabled;
        }
        public void setEnabled(Boolean enabled){
            this.enabled = enabled;
        }
        public String getType(){
            return type;
        }
        public void setType(String type){
            this.type = type;
        }
    }
    

    @RefreshScope :开启自动刷新功能。

    @ConfigurationProperties(prefix = “security.captcha”) :在配置文件中,找寻路径为security.captcha的配置信息,并读取其下的配置项,与类中的字段进行匹配。

    CaptchaProperties如何使用

    CaptchaConfig 验证码配置

    package com.ruoyi.gateway.config;
    
    import com.google.code.kaptcha.impl.DefaultKaptcha;
    import com.google.code.kaptcha.util.Config;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import java.util.Properties;
    import static com.google.code.kaptcha.Constants.*;
    
    /**
     * 验证码配置
     */
    @Configuration
    public class CaptchaConfig
    {
        @Bean(name = "captchaProducer")
        public DefaultKaptcha getKaptchaBean(){
            DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
            Properties properties = new Properties();
            // 是否有边框 默认为true 我们可以自己设置yes,no
            properties.setProperty(KAPTCHA_BORDER, "yes");
            // 验证码文本字符颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black");
            // 验证码图片宽度 默认为200
            properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
    //         验证码图片高度 默认为50
            properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
    //         验证码文本字符大小 默认为40
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38");
            // KAPTCHA_SESSION_KEY
            properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode");
            // 验证码文本字符长度 默认为5
            properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
            // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
            // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
            properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
            Config config = new Config(properties);
            defaultKaptcha.setConfig(config);
            return defaultKaptcha;
        }
            
        @Bean(name = "captchaProducerMath")
        public DefaultKaptcha getKaptchaBeanMath(){
            DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
            Properties properties = new Properties();
            // 是否有边框 默认为true 我们可以自己设置yes,no
            properties.setProperty(KAPTCHA_BORDER, "yes");
            // 边框颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90");
            // 验证码文本字符颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
            // 验证码图片宽度 默认为200
            properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
            // 验证码图片高度 默认为50
            properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
            // 验证码文本字符大小 默认为40
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "35");
            // KAPTCHA_SESSION_KEY
            properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath");
            // 验证码文本生成器
            properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "com.ruoyi.gateway.config.KaptchaTextCreator");
            // 验证码文本字符间距 默认为2
            properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3");
            // 验证码文本字符长度 默认为5
            properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6");
            // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
            // 验证码噪点颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_NOISE_COLOR, "white");
            // 干扰实现类
            properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
            // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
            properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
            Config config = new Config(properties);
            defaultKaptcha.setConfig(config);
            return defaultKaptcha;
        }
    }
    

    ValidateCodeServiceImpl 验证码实现处理

    package com.ruoyi.gateway.service.impl;
    
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.concurrent.TimeUnit;
    import javax.annotation.Resource;
    import javax.imageio.ImageIO;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.util.FastByteArrayOutputStream;
    import com.google.code.kaptcha.Producer;
    import com.ruoyi.common.core.constant.Constants;
    import com.ruoyi.common.core.exception.CaptchaException;
    import com.ruoyi.common.core.utils.IdUtils;
    import com.ruoyi.common.core.utils.StringUtils;
    import com.ruoyi.common.core.utils.sign.Base64;
    import com.ruoyi.common.core.web.domain.AjaxResult;
    import com.ruoyi.common.redis.service.RedisService;
    import com.ruoyi.gateway.config.properties.CaptchaProperties;
    import com.ruoyi.gateway.service.ValidateCodeService;
    
    /**
     * 验证码实现处理
     */
    @Service
    public class ValidateCodeServiceImpl implements ValidateCodeService
    {
        @Resource(name = "captchaProducer")
        private Producer captchaProducer;
    
        @Resource(name = "captchaProducerMath")
        private Producer captchaProducerMath;
    
        @Autowired
        private RedisService redisService;
    
        @Autowired
        private CaptchaProperties captchaProperties;
    
        /**
         * 生成验证码
         */
        @Override
        public AjaxResult createCapcha() throws IOException, CaptchaException
        {
            AjaxResult ajax = AjaxResult.success();
            boolean captchaOnOff = captchaProperties.getEnabled();
            ajax.put("captchaOnOff", captchaOnOff);
            if (!captchaOnOff)
            {
                return ajax;
            }
    
            // 保存验证码信息
            String uuid = IdUtils.simpleUUID();
            String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
    
            String capStr = null, code = null;
            BufferedImage image = null;
    
            String captchaType = captchaProperties.getType();
            // 生成验证码
            if ("math".equals(captchaType))
            {
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
                image = captchaProducerMath.createImage(capStr);
            }
            else if ("char".equals(captchaType))
            {
                capStr = code = captchaProducer.createText();
                image = captchaProducer.createImage(capStr);
            }
    
            redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            // 转换流信息写出
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            try
            {
                ImageIO.write(image, "jpg", os);
            }
            catch (IOException e)
            {
                return AjaxResult.error(e.getMessage());
            }
    
            ajax.put("uuid", uuid);
            ajax.put("img", Base64.encode(os.toByteArray()));
            return ajax;
        }
    
        /**
         * 校验验证码
         */
        @Override
        public void checkCapcha(String code, String uuid) throws CaptchaException
        {
            if (StringUtils.isEmpty(code))
            {
                throw new CaptchaException("验证码不能为空");
            }
            if (StringUtils.isEmpty(uuid))
            {
                throw new CaptchaException("验证码已失效");
            }
            String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
            String captcha = redisService.getCacheObject(verifyKey);
            redisService.deleteObject(verifyKey);
    
            if (!code.equalsIgnoreCase(captcha))
            {
                throw new CaptchaException("验证码错误");
            }
        }
    }
    
    cs