使用构造函数-arg字段填充spring bean

如何使用该字段注入包含Map的属性文件以用作其他构造函数arg。

从属性文件加载Map

bean目前使用以下方式设置:

    

Java等价物:

 Map configuration = EmbeddedGraphDatabase.loadConfigurations( "neo4j_config.props" ); GraphDatabaseService graphDb = new EmbeddedGraphDatabase( "data/neo4j-db", configuration ); 

谢谢

像这样的东西:

        

这利用了使用任意静态工厂方法创建bean的能力 ,在这种情况下使用loadConfigurations()作为工厂方法来创建configuration bean,然后将其注入到EmbeddedGraphDatabase的正确构造函数中。

创建一个加载属性的bean(并将文件名作为参数)并注入它。

编辑使用注释时,构造函数注入之类的东西变得更简单:

 @Bean public Map configuration() { return EmbeddedGraphDatabase.loadConfigurations( "neo4j_config.props" ); } @Bean public GraphDatabaseService graphDb() { return new EmbeddedGraphDatabase( "data/neo4j-db", configuration() ); } 

请注意,第二个bean定义方法“简单地”调用第一个。 当执行此代码时,Spring会做一些魔术,所以你仍然可以在别处覆盖bean(即bean仍然会相互覆盖),并且它将确保方法体只执行一次(无论多久和从哪里开始)被称为)。

如果配置在不同的@Configuration类中,那么您可以@Autowired它:

 @Autowired private Map configuration; @Bean public GraphDatabaseService graphDb() { return new EmbeddedGraphDatabase( "data/neo4j-db", configuration ); }