Spring中static变量不能@value注入的缘由

 

今天本想使用@Value的方式使类中的变量得到yml文件中的配置值,然而一直失败,得到的一直为null。redis

相似于这样写的。spring

public class RedisShardedPool {
private static ShardedJedisPool pool;//sharded jedis链接池
@Value("redis.max.total")
private static Integer maxTotal;
……
}工具

后来发现是由于这个变量是static的,而spring不支持依赖注入值到静态变量。
而后看到有人经过setter注入实现,以下.net

@Component
public class TestValue {component

public static String maxTotal;get

@Value("${redis.max.total}")
public void setDatabase(String maxTotal) {
TestValue.maxTotal= maxTotal;
}
}class

因而我也改为这种样子的,可是仍是得到不到值,由于我没在类上加@Component注解(或者相似的注解),因此spring扫描不到,也就识别不出,@Value仍是会获得null。因为我这个是工具类,里面都是static方法,调用时也都是调用类方法,因此也不须要申明为component,也不须要经过@Autowired或者@Resource调用。并且,因为这个类里面是static方法和属性,也不能经过调用其余非static的属性和方法的方式来得到值。故放弃这种实现,只好本身写一个读取配置文件的工具类,经过调用配置文件工具类类方法来解析配置文件中数据。变量

相关文章
相关标签/搜索