mongo的配置信息默认使用配置文件的spring.data.mongodb前缀的信息进行配置,但是我想另外配个其他前缀的信息如logging.data.mongodb,区分默认的mongo数据源。这个就需要建个mongo配置类,以logging.data.mongodb前缀去动态配置mongo数据源。
配置类
/*** 日志存储在mongo配置* @author lfq*/ @Configuration @EnableMongoRepositories(basePackages = "com.lfq.logging.dao", //如果有继承MongoRepository的dao层,这里需扫描使用该数据源的dao下的包mongoTemplateRef = "loggingMongoTemplate") @ConditionalOnProperty(value = "logging.dbstore.mongo.enabled", havingValue = "true") @PropertySource(value = {"classpath:application-logging.properties"}) //(这里是从application-logging.properties读取,如果不需要另外建配置文件,可以去掉) public class LoggingMonoManageConfiguration {@Bean(name = "loggingMongoProperties")@ConfigurationProperties(prefix = "logging.data.mongodb")public MongoProperties loggingMongoProperties() {return new MongoProperties();}@Bean(name = "loggingMongoTemplate")public MongoTemplate primaryMongoTemplate(@Qualifier("loggingMongoProperties") MongoProperties loggingMongoProperties) throws Exception {return new MongoTemplate(loggingManagerFactory(loggingMongoProperties));}@Bean(name = "loggingMongoManagerFactory")public MongoDbFactory loggingManagerFactory(@Qualifier("loggingMongoProperties") MongoProperties mongo){MongoClientOptions.Builder builder = new MongoClientOptions.Builder();builder.writeConcern(WriteConcern.MAJORITY);//创建一个用户认证信息MongoCredential credential = MongoCredential.createCredential(mongo.getUsername(), mongo.getDatabase(), mongo.getPassword());//封装MongoDB的地址和端口ServerAddress address = new ServerAddress(mongo.getHost(), mongo.getPort());MongoClient mongoClient = new MongoClient(address,credential,builder.build());return new SimpleMongoDbFactory(mongoClient, mongo.getDatabase());} } |