OSGi Configuration
有什么用?
admin可以直接在OSGi Configuration中进行配置,而不用在Java代码中进行修改。
OSGi Configuration中修改实则就是在改Java代码。
Interface
public interface FooterOSGi {
String[] getServiceText();
String[] getServiceValue();
}
Class
@Component
@Designate(ocd = FooterOSGiConfig.ServiceConfig.class)//这是必须的
public class FooterOSGiConfig implements FooterOSGi{
@ObjectClassDefinition(
name = "Footer Service",
description = "For Dropdown"
)
public @interface ServiceConfig{//这个注解很重要
@AttributeDefinition(//这里面的内容是让OSGi可以填的,如下图
name = "text",
description = "show name",
type = AttributeType.STRING
)
public String[] serviceText() default "A";
@AttributeDefinition(
name = "value",
description = "show value",
type = AttributeType.STRING
)
public String[] serviceValue() default "B";
}
private String[] serviceText;
private String[] serviceValue;
@Activate
protected void activate(ServiceConfig serviceConfig){//激活以后就可以取到值了
serviceText = serviceConfig.serviceText();
serviceValue = serviceConfig.serviceValue();
}
@Override
public String[] getServiceText() {
return serviceText;
}
@Override
public String[] getServiceValue() {
return serviceValue;
}
}

取值
取值我试了下,我之前写的Servlet娶不到。
但是Sling Model可以取到,
必须得注入接口来取(之前我其实没写接口,直接就写Class,然后发现取不到值,后面又给他加了个接口实现一下就可以了)
@Inject
FooterOSGi fo;
(@Inject换成@OSGiService也可以)
全新发现!
Servlet也可以取值!!!!用@Reference就可以了!!!!
然后我就取值把之前的servlet提取json的代码改了一下。就可以直接在OSGi中进行配置了
@Reference
FooterOSGi fo;
...
doGet():
//Get json path through datasource options
/*
String jsonStr = null;
Resource datasource = currentResource.getChild("datasource");
Object options = datasource.getValueMap().get("options");
Resource jsonResource = resolver.getResource(options.toString()+"/jcr:content");
jsonStr = getJsonFromFile(jsonResource);//Json to String
*/
Gson gson = new Gson();
TypeToken<List<Option>> token = new TypeToken<List<Option>>(){};
/*
List<Option> optionList = gson.fromJson(jsonStr, token.getType());
*/
List<Option> optionList = new ArrayList<>();
String[] serviceText = fo.getServiceText();
String[] serviceValue = fo.getServiceValue();
for(int i=0; i<fo.getServiceText().length; i++){
optionList.add(new Option(serviceText[i], serviceValue[i]));
}
List<Resource> optionResourceList = new ArrayList<Resource>();
/*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ replace getting json from node ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ */
知识离开了脑子,就只是一堆文字

浙公网安备 33010602011771号