热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在一种方法中正确注入Spring环境而不是另一种方法?

neo4jDatabase()很好,但是在graphDatabaseService()中环境始终为null…如何为什么?@Configuration@PropertySource(

neo4jDatabase()很好,但是在graphDatabaseService()中环境始终为null …如何/为什么?

@Configuration
@PropertySource("classpath:/neo4j.properties")
@EnableNeo4jRepositories("reservation.repository.neo4j")
public class Neo4jConfig extends Neo4jConfiguration {
@Inject
Environment environment;
@Bean(initMethod = "setupDb")
public Neo4jDatabase neo4jDatabase() {
// Environment fine here...
return new Neo4jDatabase(this.environment.getProperty("data.file.path"));
}
@Bean(destroyMethod = "shutdown")
public GraphDatabaseService graphDatabaseService() {
if (envirOnment== null) {
// Always gets here for some reason...why?
return new EmbeddedGraphDatabase("/Temp/neo4j/database");
} else {
return new EmbeddedGraphDatabase(this.environment.getProperty("database.path"));
}
}
}

版本:
Spring 3.2.0.RELEASE,spring-data-neo4j 2.1.0.RELEASE.

解决方法:

如果其他人遇到同样的问题 – 以下内容对我有用:

@Configuration
@PropertySource("classpath:neo4j.properties")
@EnableNeo4jRepositories(basePackages = "com.mydomain.neo4j.repo")
public class Neo4jConfig
{
@Autowired
Environment environment;
@Bean(name="graphDatabaseService", destroyMethod = "shutdown")
public GraphDatabaseService getGraphDatabaseService()
{
// any custom graph db initialization
return new EmbeddedGraphDatabase(this.environment.getProperty("database.path"));
}
}

注意:我没有扩展Neo4jConfiguration.它只是调整了Autowired依赖项的意大利面,其中Environment成员变量从未在graphDatabaseService初始化所需的时间设置.您可以使用@PostConstruct使其工作,但最终会出现一堆NotInTransactionException.我没有时间深入研究原因 – 相反,在您的主AppConfig类中,您只需将自定义Neo4j配置导入为基本抽象Neo4j配置类.从本质上讲,您正在使用XML配置执行的代码.

@Configuration
@Import({Neo4jConfig.class, Neo4jConfiguration.class})
@ComponentScan(basePackages = {"com.mydomain"}, excludeFilters = @Filter({Controller.class, Configuration.class}))
public class MainConfig
{
// any other configuration you have
}


推荐阅读
author-avatar
tycomed姐姐_398
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有