配置 Spring Data Neo4j 的关键在于声明 GraphDatabaseService bean 和启用 Neo4j Repository 自动生成功能。如下的程序清单展现了 Spring Data Neo4j 所需的基本配置。
程序清单 12.8 使用 @EnableNeo4jRepositories 来配置 Spring Data Neo4j
package orders.config;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
@Configuration
@EnableNeo4jRepositories(basePackages = "orders.db")
public class Neo4jConfig extends Neo4jConfiguration {
public Neo4jConfig() {
setBasePackage("orders");
}
@Bean(destroyMethod="shutdown")
public GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory()
.newEmbeddedDatabase("/tmp/graphdb");
}
}
@EnableNeo4jRepositories 注解能够让 Spring Data Neo4j 自动生成 Neo4j Repository 实现。它的 basePackages 属性设置为 orders.db 包,这样它就会扫描这个包来查找(直接或间接)扩展 Repository 标记接口的其他接口。
Neo4jConfig 扩展自 Neo4jConfiguration,后者提供了多个便利的方法来配置 Spring Data Neo4j。在这些方法中,就包括 setBasePackage(),它会在 Neo4jConfig 的构造器中调用,用来告诉 Spring Data Neo4j 要在 orders 包中查找模型类。
@Bean(destroyMethod="shutdown")
public GraphDatabaseService grapthDatabaseService() {
return new SpringRestGraphDatabser(
"http://graphdbserver:7474/db/data/");
}
@Bean(destroyMethod="shutdown")
public GraphDatabaseService grapthDatabaseService(Enviroment env) {
return new SpringRestGraphDatabser(
"http://graphdbserver:7474/db/data/",
env.getProperty("db.username"), env.getProperty("db.password"));
}
在这里,凭证是通过注入的 Environment 获取到的,避免了在配置类中的硬编码。 Spring Data Neo4j 同时还提供了 XML 命名空间。如果你更愿意在 XML 中配置 Spring Data Neo4j 的话,那可以使用该命名空间中的 <neo4j:config> 和 <neo4j:repositories> 元素。在功能上,程序清单 12.9 所展示的配置与程序清单 12.8 中的 Java 配置是相同的。