SpringBoot使用@Value给静态变量注入值

配置文件存在redis配置如下:

spring.redis.host=127.0.0.1

Java代码获取如下

@Component
public class RedisCacheUtils {
    private static final Logger logger = LoggerFactory.getLogger(RedisCacheUtils.class);
    public static JedisPool jedisPool = null;

    private static String host;

    @Value("${spring.redis.host}")
    public void setHost(String sHost) {
        host = sHost;
    }

     public static Jedis getJedis() {
        if (null == jedisPool) {
            try {
                int maxActive = Integer.valueOf(1000);
                int maxIdle = Integer.valueOf(100);
                int maxWait = Integer.valueOf(30000);
                int port = Integer.valueOf(6379);
                String pwd = "密码也能改成如上述@Value方式注入";
                JedisPoolConfig jedisConfig = new JedisPoolConfig();
                jedisConfig.setMaxTotal(maxActive);
                jedisConfig.setMaxIdle(maxIdle);
                jedisConfig.setMaxWaitMillis(maxWait);
                jedisConfig.setTestOnBorrow(true);
                jedisPool = new JedisPool(jedisConfig, host, port, 1000000, pwd);
                logger.info("jedisPool启动成功,url=" + host + ",port=" + port);
            } catch (Exception e) {
                logger.error("jedisPool启动失败", e);
            }
        }
        try {
            return jedisPool.getResource();
        } catch (Exception e) {
            logger.error("获取 Jedis失败", e);
        }
        return null;
    }
}

PS:如果直接在变了上面使用@Value,是会报Null的,相信你也是报了Null才会来查找如何注入。。

posted @ 2020-06-01 15:40  发量逐渐变少的Junner  阅读(922)  评论(0)    收藏  举报