MongoConfig.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package com.yihu.hos.rest.common.configuration;
  2. import com.mongodb.Mongo;
  3. import com.mongodb.MongoClient;
  4. import com.mongodb.MongoCredential;
  5. import com.mongodb.ServerAddress;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
  10. import static java.util.Collections.singletonList;
  11. /**
  12. * @created Airhead 2016/7/27.
  13. */
  14. @Configuration
  15. public class MongoConfig extends AbstractMongoConfiguration {
  16. @Value("${spring.data.mongodb.host}")
  17. private String host;
  18. @Value("${spring.data.mongodb.port}")
  19. private int port;
  20. @Value("${spring.data.mongodb.username}")
  21. private String username;
  22. @Value("${spring.data.mongodb.password}")
  23. private String password;
  24. @Value("${spring.data.mongodb.authenticationDatabase}")
  25. private String authenticationDatabase;
  26. @Value("${spring.data.mongodb.database}")
  27. private String database;
  28. @Override
  29. public String getDatabaseName() {
  30. return database;
  31. }
  32. @Bean
  33. public MongoClient mongoClient() throws Exception {
  34. return new MongoClient(singletonList(new ServerAddress(host, port)),
  35. singletonList(MongoCredential.createCredential(username, authenticationDatabase, password.toCharArray())));
  36. }
  37. @Bean
  38. public Mongo mongo() throws Exception {
  39. return new MongoClient(singletonList(new ServerAddress(host, port)),
  40. singletonList(MongoCredential.createCredential(username, authenticationDatabase, password.toCharArray())));
  41. }
  42. public String getHost() {
  43. return host;
  44. }
  45. public int getPort() {
  46. return port;
  47. }
  48. public String getUsername() {
  49. return username;
  50. }
  51. public String getPassword() {
  52. return password;
  53. }
  54. }