我正在尝试通过mongodb java驱动程序从spring应用程序连接它。 这是我的springDataDb Utils文件:
public class SpringDataDBUtils {
private static MongoOperations mongoOperation;
private final static Properties properties = new Properties();
private final static Logger logger = LoggerFactory.getLogger(SpringDataDBUtils.class);
public static MongoOperations getMongoOperations() throws Exception {
if( mongoOperation==null){
logger.info("Connecting to db ... ");
MongoClientURI uri = new MongoClientURI(getDatabaseURI()+getDatabaseName());
MongoClient client = new MongoClient(uri);
mongoOperation = new MongoTemplate(client, getDatabaseName());
logger.info("Connected to db : "+ getDatabaseName());
}
return mongoOperation;
/*AppConfig appConfig = new AppConfig();
return appConfig.getMongoOperations();*/
}
protected static String getDatabaseName() {
try {
InputStream inputStream = SpringDataDBUtils.class.getClassLoader()
.getResourceAsStream(AppConstant.PROPERTIES_FILE);
properties.load(inputStream);
} catch (IOException e) {
logger.error("Error:"+e.getMessage());
}
return properties.getProperty(AppConstant.PROPERTIES_DB_NAME);
}
protected static String getDatabaseURI() {
try {
InputStream inputStream = SpringDataDBUtils.class.getClassLoader().getResourceAsStream(AppConstant.PROPERTIES_FILE);
properties.load(inputStream);
} catch (IOException e) {
logger.error("Error:"+e.getMessage());
}
String dbURI = "mongodb://"+ properties.getProperty(AppConstant.PROPERTIES_DB_USER) +
":" + properties.getProperty(AppConstant.PROPERTIES_DB_PASSWORD) +
"@" + properties.getProperty(AppConstant.PROPERTIES_DB_IP) +
":" + properties.getProperty(AppConstant.PROPERTIES_DB_PORT) + "/";
logger.info(dbURI);
return dbURI;
}
public static Properties ssProperties(){
try {
InputStream inputStream = SpringDataDBUtils.class.getClassLoader()
.getResourceAsStream(AppConstant.PROPERTIES_FILE);
properties.load(inputStream);
} catch (IOException e) {
logger.error("Error:"+e.getMessage());
}
return properties;
}
}
我的属性文件是:
db.name=blooddb
db.password=****
db.user=****
db.ip= mongodb://<dbuser>:<dbpassword>@ds037587.mlab.com:37587/blooddb
db.port=27017
但是在运行应用程序时我会遇到异常。
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/istiak/blooddb/AppConfig.class]: Bean instantiation via factory method failed
这可能是我在属性文件中提供的db.ip。 那么从mLab放ip时我该怎么办?
答案 0 :(得分:1)
似乎你的dbURI字符串中存在问题。 您在dbURI中添加了两次“mongoldb://”,一个是常量字符串,另一个是从属性文件中的db.ip计算的。