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变量设为公共变量,然后按以下方式访问它:
@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() ;
}
}
答案 0 :(得分:1)
我认为最好的方法是将此变量移动到某个Constants
类
做public
并在任何需要的地方使用它。