Question

Application Context file contains

applicationContext.xml

<!-- Directs Java to correct Mongo DB address and port -->
<mongo:mongo host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="myDb" />

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />

Question 1 :: From within my classes, how would I retrieve mongo host="127.0.0.1" from the applicationContext.xml file?

Example:

String port = applicatoinContextObject.getValue("mongo host");

//which would return port="127.0.0.1"

This obviously doesn't work but this psuedo code is exactly what I would like to do.

Was it helpful?

Solution

Deepening on your spring-data-mongodb (java driver) version. You need to do something as follows:

Mongo mongo = applicationContext.getBean(Mongo.class);
String host = mongo.getConnectPoint();

The point is that you have a Mongo typed bean is your application context.

OTHER TIPS

Perhaps you may be best to externalise your environment-specific config to a properties file and then use property substitution in your applicationContext.xml. That way you can easily access the properties programatically and keep environment-specific config separate from the main Spring config.

mongo.properties

mongo.host=127.0.0.1
mongo.port=27017
mongo.dbname=myDb

applicationContext.xml

<context:property-placeholder location="classpath:/mongo.properties"/>

<!-- Directs Java to correct Mongo DB address and port -->
<mongo:mongo host="${mongo.host}" port="${mongo.port}" />
<mongo:db-factory dbname="${mongo.dbname}" />

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />

Then in your code:

Resource resource = new ClassPathResource("/mongo.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
String mongoPort = props.getProperty("mongo.port");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top