Spring: how pass values to constructor from properties file
Instead of importing your properties file using the util:properties tag, you want to import it using the context:property-placeholder. The util version simply imports the file as a Properties object, rather than exposing the property values to your configuration. So your setup would be something like:
<context:property-placeholder location="file:///storage//local.properties"/>
Then when you are wiring up your MongoService, you can use the property names in your constructor config, such as
<bean id="mongoService" class="com.business.persist.MongoService">
<constructor-arg value="${host}"/>
<constructor-arg value="${port}"/>
<constructor-arg value="${database}"/>
</bean>
See the spring docs for more details. On a side note I would consider giving a more descriptive name to each of the properties to avoid collision with other properties that might be defined in your application.
Mike and Sean gave perfectly adequate answers. Here is one addition: once your PropertyPlaceHolderConfigurer
is set up correctly, consider the nowadays widely used @Value
annotation for injecting those properties into the constructor:
public class MongoService {
..
@Autowired
public MongoService(@Value("${host}") final String host, @Value("${port}") final int port, @Value("${db}") @Nonnull final String db) throws UnknownHostException {
mongo = new Mongo(host, port);
database = db;
}
..
}
define a property placeholder:
<context:property-placeholder location="classpath:path/to/your.properties"/>
and now use the properties:
<bean id="mongoService" class="com.business.persist.MongoService">
<constructor-arg value="${property.foo}" />
<constructor-arg value="${property.bar}" />
</bean>
See: 4.8.2.1 Example: the PropertyPlaceholderConfigurer