如何覆盖SPRING BOOT Autoconfiguration提供的默认值

时间:2014-10-08 13:20:43

标签: java spring mongodb spring-data spring-boot

我对Spring 2.5开发和java有一些了解,但我正在尝试更多地了解现代Spring,包括Boot和Data。我正在看这个项目:

https://github.com/spring-projects/spring-data-examples/tree/master/rest/multi-store

我有这个例子在我的机器上工作,但我想覆盖这个例子的某些方面。例如,我想指定我自己的mongo数据库服务器和要在项目中使用的名称。似乎要做的是创建一个指定mongo数据源的新bean,但我不确定在这种情况下如何做。

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import example.person.Person;
import example.person.PersonRepository;
import example.treasure.Treasure;
import example.treasure.TreasureRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import javax.activation.DataSource;
import javax.annotation.PostConstruct;
import java.net.UnknownHostException;

/**
 * Application configuration file. Used for bootstrap and data setup.
 *
 * @author Greg Turnquist
 * @author Oliver Gierke
 */
@Configuration
@EnableAutoConfiguration
@EnableJpaRepositories
@EnableMongoRepositories
public class Application {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired PersonRepository personRepository;
    @Autowired TreasureRepository treasureRepository;

    @PostConstruct
    void checkitOut() {

        personRepository.save(new Person("Frodo", "Baggins"));
        personRepository.save(new Person("Bilbo", "Baggins"));

        for (Person person : personRepository.findAll()) {
            log.info("Hello " + person.toString());
        }

        treasureRepository.deleteAll();
        treasureRepository.save(new Treasure("Sting", "Made by the Elves"));
        treasureRepository.save(new Treasure("Sauron's ring", "One ring to rule them all"));

        for (Treasure treasure : treasureRepository.findAll()) {
            log.info("Found treasure " + treasure.toString());
        }
    }
}

2 个答案:

答案 0 :(得分:0)

请参阅MongoRepositoriesAutoConfiguration,这是自动配置发生的地方。

您可以使用Spring Boot的属性机制覆盖属性:

http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

在您的情况下,只需创建一个包含要覆盖的属性的application.properties文件:例如。 spring.data.mongo.host =,某

干杯, 马库斯

答案 1 :(得分:0)

实际属性位于我链接到http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

的文档中

马库斯提出了一个错字 - 它是spring.data.mongodb。*

我仍然不确定如何更改创建的数据库名称 - 默认似乎是" test" - 也许这是mongodb的默认设置?