Java SpringRoo:如何通过名称或id动态检索组件实例?

Java SpringRoo:如何通过名称或id动态检索组件实例?,java,osgi,spring-roo,Java,Osgi,Spring Roo,我有一个用@Component和@Service注释的类。从beans容器获取此类实例的常用方法是使用@Reference: @Reference private MyClass myclass; 如何像在SpringWeb应用程序中使用ApplicationContext那样使用字符串键检索实例?我尝试过ComponentContext.locateService,但我不知道这是否正确,也不知道必须使用哪个键值 MyClass myclass = (MyClass)context.locat

我有一个用@Component和@Service注释的类。从beans容器获取此类实例的常用方法是使用@Reference:

@Reference private MyClass myclass;
如何像在SpringWeb应用程序中使用ApplicationContext那样使用字符串键检索实例?我尝试过ComponentContext.locateService,但我不知道这是否正确,也不知道必须使用哪个键值

MyClass myclass = (MyClass)context.locateService("????"); //Which is the way?

我编辑我的问题,我会尽量解释得更好。 我有一门课是这样的:

@Component
@Service
class MySvcImpl implements MySvc { ... }
以这种方式注入:

class Main {
   @Reference private MySvc svc;

   void method1(){
       svc.doXXX();
   }
}
在这种情况下,我有一个单一的类。我希望有一堆组件子类(MySvcSubX),这样我就可以根据参数使用它们中的任何一个。据说,我不再需要@Reference行了

@Component
@Service
class MySvcSub1Impl extends MySvcImpl implements MySvc { ...}    
//The same with MySvcSub2Impl, 3, and so forth
然后在我的主课上:

void method1(String key){
    MySvc svc = callToLocateBeanById(key);
}
我不需要为每个子类添加引用,就可以通过它们的名称找到它们。

给你:

ApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath*:mySpringConfig.xml");
MyClass myClassBean =  (MyClass) context.getBean("myClass");

您可以发布具有以下属性的
@组件

@Component(property="type=xxx")
public class MyComponent implements MySvc {

}
BundleContext bc = ..;
Collection<ServiceReference<MySvc>> ref = bc.getServiceReferences(MySvc.class, "(type=xxx)")
// check cardinality, etc
MySvc svc = bc.getService(ref);
// use svc
bc.ungetService(ref);
然后使用此属性上的筛选器查询osgi注册表:

@Component(property="type=xxx")
public class MyComponent implements MySvc {

}
BundleContext bc = ..;
Collection<ServiceReference<MySvc>> ref = bc.getServiceReferences(MySvc.class, "(type=xxx)")
// check cardinality, etc
MySvc svc = bc.getService(ref);
// use svc
bc.ungetService(ref);
旧答案

您应该使用引用的名称。此名称可以在
@Reference
中指定,但默认值是由属性名称或bind/unbind方法生成的(有关此注释,请参阅javadoc)

在您的示例中,应该是:

MyClass myclass = (MyClass)context.locateService("myClass");

如果您不确定,可以查看从组件生成的xml,您将看到生成的名称。

如果我正确理解了这个问题,它与osgi声明服务相关,而不是spring。但是我不知道为什么会有SpringRoo标签:-)SpringRoo标签是因为我正在开发一个插件。SpringRoo插件使用OSGi功能,RooShell使用OSGi命令安装它们。谢谢,我会尝试,但我不确定这是否是我想要的。我已经扩展了我的问题文本来解释这一点。最后添加的问题对我来说没有任何意义。你能试着用不同的方式解释吗?嗨,杰米,你的方法很有效,但正如我所说,我认为这并不是我想要的。谢谢你,听起来不错。我会尽量告诉你的。谢谢