Question

How can i inject a properties file containing a Map to be used as additional constructor arg using the field.

With a Map being loaded from a properties file

the bean is currently setup using:

<bean id="graphDbService" class="org.neo4j.kernel.EmbeddedGraphDatabase"
     init-method="enableRemoteShell" destroy-method="shutdown">

     <constructor-arg index="0" value= "data/neo4j-db"/>
         <constructor-arg index="1" value=?  />
</bean>

Java Equivalent:

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

Thanks

Was it helpful?

Solution

Something like this:

<bean id="configuration" class="org.neo4j.kernel.EmbeddedGraphDatabase" 
      factory-method="loadConfigurations">
   <constructor-arg value="neo4j_config.props"/>
</bean>

<bean id="graphDbService" class="org.neo4j.kernel.EmbeddedGraphDatabase"
     init-method="enableRemoteShell" destroy-method="shutdown">

     <constructor-arg index="0" value="data/neo4j-db"/>
     <constructor-arg index="1" ref="configuration"  />
</bean>

This takes advantage of the ability to create beans using arbitrary static factory methods, in this case using loadConfigurations() as a factory method to create the configuration bean, which is then injected into the proper constructor of EmbeddedGraphDatabase.

OTHER TIPS

Create a bean that loads the properties (and takes the file name as an argument) and inject that instead.

EDIT When using annotations, things like constructor injection become more simple:

@Bean
public Map<String,String> configuration() {
    return EmbeddedGraphDatabase.loadConfigurations( "neo4j_config.props" );
}

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

Note that the second bean definition method "simply" calls the first. When this code is executed, Spring will do some magic so you can still override the bean elsewhere (i.e. beans still overwrite each other) and it will make sure that the method body will be executed only once (no matter how often and from where it was called).

If the config is in a different @Configuration class, then you can @Autowired it:

@Autowired
private Map<String,String> configuration;

@Bean
public GraphDatabaseService graphDb() {
    return new EmbeddedGraphDatabase( "data/neo4j-db", configuration );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top