我们学习过将配置信息,通过@Value()的方法注入到对象的变量。这是由于对象是由spring来托管的。那么非spring如果,我们需要在静态方法中,使用配置文件中的值,又该怎么做呢?
传统的错误作法
application.properties
spring.redis.host=test@Componentpublic class RedisServiceImpl implements RedisService { ... @Value("${spring.redis.host}") static public String host; @Value("${spring.redis.port}") static public Integer port; ... static public JedisPool getJedisPool() { if (RedisServiceImpl.host == null) { logger.info("host 未注入"); } }控制台打印为: "host 未注入
正确的方法
控制台正确的打印了注入的值。
原因猜想
spring进行组件扫描,遇到@Component时,初始化对象 RedisServiceImpl, 初始化过程中,扫描到@Value注解,将值注入给方法。
接着,方法将值传给了RedisServiceImpl类,故RedisServiceImpl有值 -- 正解。
如果将@Value(),直接加到静态私有变量上,则在初始化对象时,由于静态私有变量属于类,所以spring未对类进行操作 -- 错误。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。