zoukankan      html  css  js  c++  java
  • springboot @vaule注解失效解决办法

    在Controller类里面通过@Value将参数注入进来,最后的确成功了。因此基于此经验,我便在其他使用的类里面也采用这样的方式注入参数,但是发现去失效了,报错为NULL,说明参数并没有我们料想的被注入进来。

    原因 这是为什么呢?为什么在Controller类就成功了?在其他类里面我尝试过@Service,@Component,@Configure,但是我没有成功,经过查询,原来,在使用这些参数生成Bean类的时候,我们注入的参数还没有生效,因此获取不到,而不是由于参数注入的问题,而在某些场景,spring可能做了优化,是的参数优先注入,再生成Bean。那么有没有好的方法可以解决这个问题呢? 方案 首先,我们的参数的直接注入是肯定不行了,那么我们就采用初始化类的方式,将配置信息集中初始化。

    import lombok.extern.slf4j.Slf4j;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    /**
     * 为bean类提前注入属性
     */
    @Slf4j
    public class PropertyUtil {
    
        private static Properties props;
    
        static {
            loadProps();
        }
    
        synchronized static private void loadProps() {
            log.info("start to load properties.......");
            props = new Properties();
            InputStream in = null;
            try {
    
                in = PropertyUtil.class.getClassLoader().
                        getResourceAsStream("application.properties");
                props.load(in);
                log.info("");
            } catch (FileNotFoundException e) {
                log.error("properties not found!");
            } catch (IOException e) {
                log.error("IOException");
            } finally {
                try {
                    if (null != in) {
                        in.close();
                    }
                } catch (IOException e) {
                    log.error("properties close Exception!");
                }
            }
            // logger.info(props);
            log.info("load properties over...........");
        }
    
        public static String getProperty(String key) {
            if (null == props) {
                loadProps();
            }
            return props.getProperty(key);
        }
    }

    使用方法:

     private static String reqIp = PropertyUtil.getProperty("reqIp");
  • 相关阅读:
    c语言--第零次作业
    Beta 冲刺(3/7)
    Beta 冲刺(2/7)
    福大软工 · 第十次作业
    Beta 冲刺(1/7)
    BETA 版冲刺前准备(团队)
    Alpha 事后诸葛亮(团队)
    Alpha冲刺(10/10)
    Alpha 冲刺 (9/10)
    Alpha 冲刺 (8/10)
  • 原文地址:https://www.cnblogs.com/chenziyu/p/9688979.html
Copyright © 2011-2022 走看看