开发者

Populating a spring bean using a constructor-arg field

开发者 https://www.devze.com 2023-01-11 11:29 出处:网络
How can i inject a properties file containing a Map to be used as additional constructor arg using thefield.

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:

开发者_如何学Go
Map<String,String> configuration =  EmbeddedGraphDatabase.loadConfigurations( "neo4j_config.props" );
GraphDatabaseService graphDb = new EmbeddedGraphDatabase( "data/neo4j-db", configuration );

Thanks


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.


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 );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消