我正在尝试在OSGi中运行一个包,在一个类中我正在使用@Inject注释。 Build是成功的,但变量indexerConfiguration仍为null。为什么呢?
@Named
@Singleton
public class IndexerConfiguration
{
private Indexer indexer;
private Scanner scanner;
private Map<String, IndexCreator> indexers;
@Inject
public IndexerConfiguration( Indexer indexer,
Scanner scanner,
Map<String, IndexCreator> indexers ){
this.indexer = indexer;
this.scanner = scanner;
this.indexers = indexers;
}
public Indexer getIndexer(){
return indexer;
}
第二个类在同一个包中:
public class MyFactory implements ManagedServiceFactory {
public static final String PID = "myPid";
private volatile DependencyManager m_dependencyManager;
private final Map<String, Component> m_components = new HashMap<String, Component>();
@Inject
private IndexerConfiguration indexerConfiguration;
@Override
public String getName() {
return "myBundle";
}
@Override
public void updated(String pid,
@SuppressWarnings("rawtypes") Dictionary properties)
throws ConfigurationException {
if (m_components.containsKey(pid)) {
return;
}
Component component = m_dependencyManager
.createComponent()
.setImplementation(myOwnClass.class)
.add(m_dependencyManager.createConfigurationDependency()
.setPid(pid));
indexerConfiguration.getIndexer(); //this is still null :( why?
m_components.put(pid, component);
m_dependencyManager.add(component);
}
所有进口都没问题,构建是成功的,但为什么注射不起作用?谢谢
答案 0 :(得分:1)
有一些方法可以在OSGi中使用@Inject。
一种是使用pax-cdi来适应CDI框架OpenWebBeans或Weld for OSGi。这里的好处是它旨在完全支持CDI标准。目前的缺点是它在某些角落仍然有点实验性,比如jpa支持。
另一个是使用白羊座的blueprint-maven-plugin。它支持CDI的一小部分,并在编译时将其映射到蓝图上下文。这里的优点是它已经支持jpa,你可以将它与手写蓝图结合起来实现更复杂的案例,并利用apache cxf等蓝图扩展来实现webservices和apache camel的集成。缺点是它只支持CDI的一小部分,尚未有详细记录。它仍然运行良好,我已经在一个大型客户项目中使用它从spring / tomcat迁移到blueprint / OSGi。 我有一个小示例项目tasklist-blueprint-cdi at github。我计划很快就做一个关于它的教程。
如果所有这些对您来说都太具有实验性,那么OSGi中DI和服务的成熟解决方案就是蓝图和声明式服务。但它们有其自身的局限性。