Как отключить автоконфигурирование spring-data-mongodb в spring-boot

Кто-нибудь пробовал отключить автоконфигурацию для mongodb в spring-boot?

Я пробую Spring-Boot с Spring-Data-Mongodb; Использование конфигурации на основе Java; Используя spring-boot 1.2.1.RELEASE, я импортирую spring-boot-starter-web и его родительский pom для управления зависимостями. Я также импортирую spring-data-mongodb (пробовал также spring-boot-starter-mongodb).

Мне нужно подключиться к двум различным серверам MongoDB. Поэтому мне нужно настроить два набора экземпляров для монго-соединения, MongoTemplate и т. Д. Я также хочу отключить автоконфигурацию. Поскольку я подключаюсь к нескольким серверам, мне не нужно автоматически настраивать один компонент по умолчанию MongoTemplate и GridFsTemplate.

Мой основной класс выглядит так:

@Configuration
@EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@ComponentScan
//@SpringBootApplication // @Configuration @EnableAutoConfiguration @ComponentScan 
public class MainRunner {

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

Мои два класса конфигурации Монго выглядят так:

@Configuration
@EnableMongoRepositories(basePackageClasses = {Test1Repository.class},
        mongoTemplateRef = "template1",
        includeFilters = {@ComponentScan.Filter(type = FilterType.REGEX, pattern = ".*Test1Repository")}
)
public class Mongo1Config {

    @Bean
    public Mongo mongo1() throws UnknownHostException {
        return new Mongo("localhost", 27017);
    }

    @Primary
    @Bean
    public MongoDbFactory mongoDbFactory1() throws UnknownHostException {
        return new SimpleMongoDbFactory(mongo1(), "test1");
    }

    @Primary
    @Bean
    public MongoTemplate template1() throws UnknownHostException {
        return new MongoTemplate(mongoDbFactory1());
    }
}

а также

@Configuration
@EnableMongoRepositories(basePackageClasses = {Test2Repository.class},
        mongoTemplateRef = "template2",
        includeFilters = {@ComponentScan.Filter(type = FilterType.REGEX, pattern = ".*Test2Repository")}
)
public class Mongo2Config {

    @Bean
    public Mongo mongo2() throws UnknownHostException {
        return new Mongo("localhost", 27017);
    }

    @Bean
    public MongoDbFactory mongoDbFactory2() throws UnknownHostException {
        return new SimpleMongoDbFactory(mongo2(), "test2");
    }

    @Bean
    public MongoTemplate template2() throws UnknownHostException {
        return new MongoTemplate(mongoDbFactory2());
    }
}

С этой настройкой все работает. Если я удалю аннотации @Primary из bean-компонентов mongoDbFactory1 и template1, приложение завершится ошибкой, за исключением того, что автоконфигурация не отключена. Сообщение об исключении указано ниже:

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:474)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:961)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:950)
    at com.fourexpand.buzz.web.api.template.MainRunner.main(MainRunner.java:26)
Caused by: org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.initialize(TomcatEmbeddedServletContainer.java:98)
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.<init>(TomcatEmbeddedServletContainer.java:75)
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getTomcatEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:378)
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:155)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:157)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130)
    ... 7 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter': Injection of autowired dependencies failed; nested exception is  org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.core.io.ResourceLoader org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.resourceLoader; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'gridFsTemplate' defined in class path resource [org/springframework/boot/autoconfigure/mongo/MongoDataAutoConfiguration.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.data.mongodb.MongoDbFactory]: : No qualifying bean of type [org.springframework.data.mongodb.MongoDbFactory] is defined: expected single matching bean but found 2: mongoDbFactory2,mongoDbFactory1; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.data.mongodb.MongoDbFactory] is defined: expected single matching bean but found 2: mongoDbFactory2,mongoDbFactory1

4 ответа

Решение

Как отметил Энди Уилкинсон в комментариях, при использовании EnableAutoConfiguration со списком исключений убедитесь, что нет других классов, аннотированных с помощью EnableAutoConfiguration или SpringBootApplication.

Вот как я это делаю:

@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})

Попробуйте запустить приложение в режиме отладки. Это происходит, когда зависимая конфигурация MongoDB пытается создать экземпляр, но соответствующий бин отсутствует. В моем случае я исключил MongoDataAutoConfiguration.class и MongoRepositoriesAutoConfiguration.class, чтобы запустить приложение.

@SpringBootApplication @EnableAutoConfiguration(exclude={MongoAutoConfiguration.class, MongoRepositoriesAutoConfiguration .class,MongoDataAutoConfiguration.class}) public class SomeApplication { //... }

Мой вариант использования был немного другим. У меня была потребность в 2 разных базах данных в одном проекте. Я расширил классы автоконфигурации и добавил аннотацию профиля.

@Profile("mongo")
@Configuration
public class CustomMongoAutoConfiguration extends MongoAutoConfiguration {

    public CustomMongoAutoConfiguration(
        MongoProperties properties,
        ObjectProvider<MongoClientOptions> options,
        Environment environment) {
        super(properties,options,environment);
    }
}

А также

@Profile("mongo")
@Configuration
@EnableConfigurationProperties(MongoProperties.class)
public class CustomMongoDataAutoConfiguration extends MongoDataAutoConfiguration {

    public CustomMongoDataAutoConfiguration(
        ApplicationContext applicationContext,
        MongoProperties properties) {
        super(applicationContext,properties);
    }

}

Весенняя загрузка 2.3.x:

spring.autoconfigure.exclude[0]: org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration
spring.autoconfigure.exclude[1]: org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration

Реактивный:

spring.autoconfigure.exclude[0]: org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration
spring.autoconfigure.exclude[1]: org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration

То же, что и /questions/43498652/kak-otklyuchit-avtokonfigurirovanie-spring-data-mongodb-v-spring-boot/43498657#43498657 с /questions/43498652/kak-otklyuchit-avtokonfigurirovanie-spring-data-mongodb-v-spring-boot/43498654#43498654, Spring boot 2.3 / Kotlin

@SpringBootApplication(exclude = [MongoAutoConfiguration::class, MongoDataAutoConfiguration::class]
@Profile("mongo")
@Configuration
class CustomMongoAutoConfiguration: MongoAutoConfiguration() {
    override fun mongo(
        properties: MongoProperties?,
        environment: Environment?,
        builderCustomizers: ObjectProvider<MongoClientSettingsBuilderCustomizer>?,
        settings: ObjectProvider<MongoClientSettings>?
    ): MongoClient {
        return super.mongo(properties, environment, builderCustomizers, settings)
    }
}
@Profile("mongo")
@Configuration
@EnableConfigurationProperties(MongoProperties::class)
class CustomMongoDataAutoConfiguration : MongoDataAutoConfiguration()
Другие вопросы по тегам