其他分享
首页 > 其他分享> > 如何在一种方法中正确注入Spring环境而不是另一种方法?

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

作者:互联网

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
}

标签:spring,spring-annotations,spring-data-neo4j
来源: https://codeday.me/bug/20190709/1411583.html