咱们学习过将配置信息经过@Value()
的方法注入到对象的变量中。这是因为对象是由spring
统一托管的(保证了单例模式)。那于对于非spring
托管的类,若是注入注入数据呢?java
好比:咱们想把配置信息的值,注入到类的静态变量中。redis
application.propertiesspring
spring.redis.host=test
@Component public 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 未注入app
@Component public class RedisServiceImpl implements RedisService { ... static public String host; static public Integer port; @Value("${spring.redis.host}") public void setHost(String host) { RedisServiceImpl.host = host; } @Value("${spring.redis.port}") public void setPort(Integer port) { RedisServiceImpl.port = port; } ... static public JedisPool getJedisPool() { if (RedisServiceImpl.host == null) { logger.info("host 未注入"); } else { logger.info("host 值为" + RedisServiceImpl.host); } }
控制台正确的打印了注入的值。学习
spring
在启动时会进行组件扫描,打描到RedisServiceImpl
时,发现其类使用了@Component
注解。因而,初始化对象 RedisServiceImpl
。初始化过程当中,对方法进行扫描,当扫描到使用@Value
注解的方法时,调用方法,并注入须要注入的值。code
而后:咱们使用了一个小的技巧: 在这个自动执行的方法中,将值设置给了类。进而实现了,在启动时将值注入
到类的目标。对象
其实:spring
不对类进行托管,因此也就不可能将值注入到类。因此咱们的上述方法,应该描述为:将值注入给方法,而后在方法中,使用传入的值为类进行数据初始化。get
这时,咱们也就清楚为何使用@Value()
注解时,没法将值注入的缘由了:
若是将@Value()
,直接加到静态私有变量上,则在初始化对象时,因为静态私有变量属于类,因此spring
未对类进行操做 -- 错误。io