如何通过Neo4j非托管扩展中的@Context提供服务
我有Neo4j非托管扩展。 我希望将一些服务创建为单例,并在我的资源中通过@Context
提供。
像这样的东西:
@Path("/example") public class ExampleResource { public ExampleResource(@Context CostlyService costlyService) { // <<--- // use it here } }
如何实现这一目标?
Neo4j具有PluginLifecycle接口,使我们可以挂钩Neo4j服务器生命周期并为注入博客post提供我们自己的服务。
所以,我们有服务。 我们以此为例:
public interface CostlyService { } public class CostlyServiceImpl implements CostlyService { public CostlyService() { // a LOT of work done here } //... }
现在我们需要创建自己的PluginLifecycle
实现:
public class ExamplePluginLifecycle implements PluginLifecycle { @Override public Collection> start(GraphDatabaseService graphDatabaseService, Configuration config) { final List> injectables = new ArrayList<>(); return injectables; } @Override public void stop() { } }
如您所见,可注射列表现在是空的。 我们很快就会加入我们的服务。
重要提示:您必须注册PluginLifecycle
实现,以便通过SPI提供:
// file: META-INF/services/org.neo4j.server.plugins.PluginLifecycle my.company.extension.ExamplePluginLifecycle
这将使您的PluginLifecycle
被Neo4j服务器发现。
现在我们需要创建实际的注射剂。 让我们为Injectable
接口编写实现:
public final class TypedInjectable implements Injectable { private final T value; private final Class type; private TypedInjectable(final T value, final Class type) { this.value = value; this.type = type; } public static TypedInjectable injectable(final T value, final Class type) { return new TypedInjectable<>(value, type); } @Override public T getValue() { return value; } @Override public Class getType() { return type; } }
这将作为我们服务的简单容器。 用法:
import static my.company.extension.TypedInjectable.injectable; injectable(new CostlyServiceImpl(), CostlyService.class);
现在我们可以将我的注射剂添加到PluginLifecycle
。
@Override public Collection> start(GraphDatabaseService graphDatabaseService, Configuration config) { final List> injectables = new ArrayList<>(); injectables.add(injectable(new CostlyServiceImpl, CostlyService.class)); // <<--- return injectables; }
在此更改之后,我们的CostlyService将通过@Context用于我们的资源:
@Path("/example") public class ExampleResource { public ExampleResource(@Context CostlyService costlyService) { // use it here } // ... }
提示 :将PluginLifecycle保存在与您的资源相同的包或子包中。