Neo4j具有PluginLifecycle接口,这使我们有可能进入Neo4j服务器生命周期,并为注入博客文章提供我们自己的服务。
因此,我们有服务。让我们以这个为例:
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<Injectable<?>> start(GraphDatabaseService graphDatabaseService, Configuration config) { final List<Injectable<?>> injectables = new ArrayList<>(); return injectables; } @Override public void stop() { }}如您所见,可注射列表目前为空。我们将很快在那里添加我们的服务。
重要提示: 您必须注册您的
PluginLifecycle实现,因此可以通过SPI使用:
// file: meta-INF/services/org.neo4j.server.plugins.PluginLifecyclemy.company.extension.ExamplePluginLifecycle
这将使
PluginLifecycleNeo4j服务器可以发现您。
现在我们需要创建实际的注射剂。让我们为
Injectable接口编写实现:
public final class TypedInjectable<T> implements Injectable<T> { private final T value; private final Class<T> type; private TypedInjectable(final T value, final Class<T> type) { this.value = value; this.type = type; } public static <T> TypedInjectable<T> injectable(final T value, final Class<T> type) { return new TypedInjectable<>(value, type); } @Override public T getValue() { return value; } @Override public Class<T> getType() { return type; }}这将作为我们服务的简单容器。用法:
import static my.company.extension.TypedInjectable.injectable;injectable(new CostlyServiceImpl(), CostlyService.class);
现在,我们可以将注射剂添加到中了
PluginLifecycle。
@Overridepublic Collection<Injectable<?>> start(GraphDatabaseService graphDatabaseService, Configuration config) { final List<Injectable<?>> 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与资源一起放在同一包或子包中。



