我有一个util类,内部有一个feign,一个静态的方法,代码如下:
public class someUitl {
@Resource
private SomeFeign someFeign;
static public Object someMethod() {
someFeign.otherMethod();
}
}
如果这样子写会报错,原因是:
静态方法不能直接访问非静态实例变量,因为静态方法属于类,而实例变量属于类的实例。为了在静态方法中使用类的变量,你需要确保这些变量也是静态的,或者通过其他方式(如传递参数)来访问实例变量。
由于这是一个工具类,类的实例是唯一的,我可以直接使用单例模式管理变量,代码修改如下:
public class SomeUitl {
@Resource
private SomeFeign someFeign;
// 增加一个静态变量
private static SomeUtil instance;
static public Object someMethod() {
SomeUtil intance = getInstance();
instance.someFeign.otherMethod();
}
/**
* 获取单例示例
*/
private static SomeUtil getInstance() {
if (instance == null) {
intance = new SomeUtil();
}
return instance;
}
}