【发布时间】:2015-01-09 18:11:12
【问题描述】:
我有一些 Java 代码,我想通过依赖注入将其转换为可在 Grails 控制器和服务中使用的 Bean。该代码基于 here(作为独立 Java 应用程序运行时可以正常工作)。
具体来说,我有:
// WannabeABeanDB.java
package hello;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.impl.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;
import org.springframework.data.neo4j.core.GraphDatabase;
import java.io.File;
@Component
@Configuration
@EnableNeo4jRepositories(basePackages = "hello")
public class WannabeABeanDB extends Neo4jConfiguration {
public WannabeABeanDB() {
setBasePackage("hello");
}
@Bean
GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabase("accessingdataneo4j.db");
}
@Autowired
PersonRepository personRepository;
@Autowired
GraphDatabase graphDatabase;
public String testThatWeCanAccessDatabase() throws Exception {
Person greg = new Person("Greg");
Transaction tx = graphDatabase.beginTx();
try {
personRepository.save(greg);
greg = personRepository.findByName("Greg").toString();
tx.success();
} finally {
tx.close();
}
return greg.name;
}
}
// Person.java
package hello;
import java.util.HashSet;
import java.util.Set;
import org.neo4j.graphdb.Direction;
import org.springframework.data.neo4j.annotation.Fetch;
import org.springframework.data.neo4j.annotation.GraphId;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;
@NodeEntity
public class Person {
@GraphId Long id;
public String name;
public Person() {}
public Person(String name) { this.name = name; }
public String toString() {
return this.name;
}
}
// PersonRepository.java
package hello;
import org.springframework.data.repository.CrudRepository;
public interface PersonRepository extends CrudRepository<Person, String> {
Person findByName(String name);
}
所以现在我想从控制器中使用:
// TestController.groovy
package hello
import hello.WannabeABeanDB
class TestController {
WannabeABeanDB graph
def index() {
render graph.test()
}
}
我已经设置(在 Config.groovy 中):
grails.spring.bean.packages = ['hello']
但是,当我执行 grails 运行应用程序时,Grails 崩溃并显示一条很长的错误消息,指出它无法与空数据库一起使用。我不相信PersonRepository 或graphDatabase 都会使用@Autowire。
所以问题是,我还需要做些什么才能将使用 Java 代码(在 src/java 中)编写为 Grails 控制器或服务中的 Bean?
【问题讨论】:
标签: java spring grails spring-data spring-data-neo4j