• Spring boot中使用工具类 无需注入获取properties 中的值


    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.core.env.Environment;
    import org.springframework.stereotype.Component;
    
    import java.io.IOException;
    import java.util.MissingResourceException;
    
    @Component
    public final class PropertiesUtil {
    
        public static final byte[] KEY = { 9, -1, 0, 5, 39, 8, 6, 19 };
        private static Environment env;
    
        @Autowired
        protected void set(Environment env) throws IOException {
            PropertiesUtil.env = env;
        }
    
        /**
         * Get a value based on key , if key does not exist , null is returned
         * 
         * @param key
         * @return
         */
        public static String getString(String key) {
            try {
                return env.getProperty(key);
            } catch (MissingResourceException e) {
                return null;
            }
        }
    
        /**
         * Get a value based on key , if key does not exist , null is returned
         * 
         * @param key
         * @return
         */
        public static String getString(String key, String defaultValue) {
            try {
                String value = env.getProperty(key);
                if (value == null) {
                    return defaultValue;
                }
                return value;
            } catch (MissingResourceException e) {
                return defaultValue;
            }
        }
    
        /**
         * 根据key获取值
         * 
         * @param key
         * @return
         */
        public static int getInt(String key) {
            return Integer.parseInt(env.getProperty(key));
        }
    
        /**
         * 根据key获取值
         * 
         * @param key
         * @param defaultValue
         * @return
         */
        public static int getInt(String key, int defaultValue) {
            String value = env.getProperty(key);
            if (StringUtils.isBlank(value)) {
                return defaultValue;
            }
            return Integer.parseInt(value);
        }
    
        /**
         * 根据key获取值
         * 
         * @param key
         * @param defaultValue
         * @return
         */
        public static boolean getBoolean(String key, boolean defaultValue) {
            String value = env.getProperty(key);
            if (StringUtils.isBlank(value)) {
                return defaultValue;
            }
            return new Boolean(value);
        }
    }

    使用

    参考:https://blog.csdn.net/u011249282/article/details/80213880

  • 相关阅读:
    javascript优化--10模式(设计模式)01
    javascript优化--09模式(代码复用)02
    限制字符个数显示
    title
    点选词高亮算法
    ng-repeat嵌套的$index
    console.log的问题
    outsideClick 功能,探索
    input 框的 placeholder 另类实现
    ie9 与 placeholder 问题
  • 原文地址:https://www.cnblogs.com/lyon91/p/10395707.html
Copyright © 2020-2023  润新知