Java 访问服务组件中静态变量的好方法
现在,要获取XYZHelper中DEMO变量的值,以下哪种方法是好的: 方法1:将DEMO变量公开,然后按如下方式访问它:Java 访问服务组件中静态变量的好方法,java,spring,components,Java,Spring,Components,现在,要获取XYZHelper中DEMO变量的值,以下哪种方法是好的: 方法1:将DEMO变量公开,然后按如下方式访问它: public interface ABCHelper { ... ... } @Service(ABCHelper.class) @Component(immediate = true, metatype = true) public class ABCHelperImpl implements ABCHelpe
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;
...
...
}
@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中定义静态方法,然后按如下方式进行处理:
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;
...
...
}
@Service(XYZ.class)
@Component(immediate = true, metatype = true)
public class XYZHelperImpl implements XYZHelper {
@Reference private ABCHelper abcHelper;
...
...
void f() {
String s = ABCHelperImpl.DEMO ;
}
}
方法3:
@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() ;
}
}
我认为最好的方法是将这个变量移动到一些
常量
类
使用它public
并在任何需要的地方使用它