1、在resources文件下创建配置文件database.properties
mongodb.uri=xxxxxxxxxx
mongodb.username=ceshi
mongodb.password=123456
mongodb.schema=xxxxx
2、在mogodb配置方法中读取配置文件信息
@Configuration //等价于XML中配置bean
@PropertySource(value = "classpath:database.properties",ignoreResourceNotFound = true)
public class MongoDBConfig {
@Value("${mongodb.schema}")
private String databaseName;
@Value("${mongodb.uri}")
private String uri;
@Value("${mongodb.username}")
private String userName;
@Value("${mongodb.password}")
private String password;
@Bean
public MongoDbFactory mongoDbFactory() throws UnknownHostException {
String uriStr="mongodb://"+userName+":"+password+"@"+uri+"/"+databaseName;
System.out.println(uriStr);
MongoClientURI mongoClientURI=new MongoClientURI(uriStr);
MongoDbFactory mongoDbFactory=new SimpleMongoDbFactory(mongoClientURI);
return mongoDbFactory;
}
}
网友评论