gpt4 book ai didi

java - 访问服务组件中的静态变量的好方法

转载 作者:行者123 更新时间:2023-11-30 07:36:33 25 4
gpt4 key购买 nike

 public interface ABCHelper { 
...
...
}

@Service(ABCHelper.class)
@Component(immediate = true, metatype = true)
public class ABCHelperImpl implements ABCHelper {
private static String DEMO = "demo";
...
...
}


@Service(XYZ.class)
@Component(immediate = true, metatype = true)
public class XYZHelperImpl implements XYZHelper {
@Reference private ABCHelper abcHelper;
...
...
}

现在要获取 XYZHelper 中 DEMO 变量的值,以下哪种方法比较好:

方法1:将DEMO变量设置为公共(public)变量,然后按如下方式访问它:

@Service(XYZ.class)
@Component(immediate = true, metatype = true)
public class XYZHelperImpl implements XYZHelper {
@Reference private ABCHelper abcHelper;
...
...
void f() {
String s = ABCHelperImpl.DEMO ;
}
}

方法2:在ABCHelperImpl中定义静态方法,然后按如下方式处理它:

@Service(ABCHelper.class)
@Component(immediate = true, metatype = true)
public class ABCHelperImpl implements ABCHelper {
private static String DEMO = "demo";
...
...
public static String getDemo() {
return DEMO;
}
}

@Service(XYZ.class)
@Component(immediate = true, metatype = true)
public class XYZHelperImpl implements XYZHelper {
@Reference private ABCHelper abcHelper;
...
...
void f() {
String s = ABCHelperImpl.getDemo() ;
}
}

方法 3:

public interface ABCHelper { 
...
...
public String getDemo();
}

@Service(ABCHelper.class)
@Component(immediate = true, metatype = true)
public class ABCHelperImpl implements ABCHelper {
private static String DEMO = "demo";
...
...
public static String getDemo() {
return DEMO;
}
}

@Service(XYZ.class)
@Component(immediate = true, metatype = true)
public class XYZHelperImpl implements XYZHelper {
@Reference private ABCHelper abcHelper;
...
...
void f() {
String s = abcHelper.getDemo() ;
}
}

最佳答案

我认为最好的方法是将这个变量移动到某个Constants公开并在您需要的任何地方使用它。

关于java - 访问服务组件中的静态变量的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35314011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com