001/*
002 * Copyright 2012-2016 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 java.net.UnknownHostException;
020
021import javax.annotation.PreDestroy;
022
023import com.mongodb.MongoClient;
024import com.mongodb.MongoClientOptions;
025
026import org.springframework.beans.factory.ObjectProvider;
027import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
028import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
029import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
030import org.springframework.boot.context.properties.EnableConfigurationProperties;
031import org.springframework.context.annotation.Bean;
032import org.springframework.context.annotation.Configuration;
033import org.springframework.core.env.Environment;
034
035/**
036 * {@link EnableAutoConfiguration Auto-configuration} for Mongo.
037 *
038 * @author Dave Syer
039 * @author Oliver Gierke
040 * @author Phillip Webb
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 MongoProperties properties;
049
050        private final MongoClientOptions options;
051
052        private final Environment environment;
053
054        private MongoClient mongo;
055
056        public MongoAutoConfiguration(MongoProperties properties,
057                        ObjectProvider<MongoClientOptions> options, Environment environment) {
058                this.properties = properties;
059                this.options = options.getIfAvailable();
060                this.environment = environment;
061        }
062
063        @PreDestroy
064        public void close() {
065                if (this.mongo != null) {
066                        this.mongo.close();
067                }
068        }
069
070        @Bean
071        @ConditionalOnMissingBean
072        public MongoClient mongo() throws UnknownHostException {
073                this.mongo = this.properties.createMongoClient(this.options, this.environment);
074                return this.mongo;
075        }
076
077}