001/* 002 * Copyright 2012-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.autoconfigure.mongo; 018 019import javax.annotation.PreDestroy; 020 021import com.mongodb.MongoClient; 022import com.mongodb.MongoClientOptions; 023 024import org.springframework.beans.factory.ObjectProvider; 025import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 026import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 027import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 028import org.springframework.boot.context.properties.EnableConfigurationProperties; 029import org.springframework.context.annotation.Bean; 030import org.springframework.context.annotation.Configuration; 031import org.springframework.core.env.Environment; 032 033/** 034 * {@link EnableAutoConfiguration Auto-configuration} for Mongo. 035 * 036 * @author Dave Syer 037 * @author Oliver Gierke 038 * @author Phillip Webb 039 * @author Mark Paluch 040 * @author Stephane Nicoll 041 */ 042@Configuration 043@ConditionalOnClass(MongoClient.class) 044@EnableConfigurationProperties(MongoProperties.class) 045@ConditionalOnMissingBean(type = "org.springframework.data.mongodb.MongoDbFactory") 046public class MongoAutoConfiguration { 047 048 private final MongoClientOptions options; 049 050 private final MongoClientFactory factory; 051 052 private MongoClient mongo; 053 054 public MongoAutoConfiguration(MongoProperties properties, 055 ObjectProvider<MongoClientOptions> options, Environment environment) { 056 this.options = options.getIfAvailable(); 057 this.factory = new MongoClientFactory(properties, environment); 058 } 059 060 @PreDestroy 061 public void close() { 062 if (this.mongo != null) { 063 this.mongo.close(); 064 } 065 } 066 067 @Bean 068 @ConditionalOnMissingBean(type = { "com.mongodb.MongoClient", 069 "com.mongodb.client.MongoClient" }) 070 public MongoClient mongo() { 071 this.mongo = this.factory.createMongoClient(this.options); 072 return this.mongo; 073 } 074 075}