2016-02-10 64 views
1
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() ; 
     } 
} 

回答

1

我認爲最好的辦法將是這個變量移動到一些Constants 類做public到處都需要使用它。