SpringBoot排除自动加载数据源方式

 更新时间:2024年05月29日 09:29:55   作者:fenglllle  
这篇文章主要介绍了SpringBoot排除自动加载数据源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

前言

有些老项目使用Spring MVC里面有写好的数据库连接池,比如redis/mongodb/mybatis(mysql其他Oracle同理)。

在这些项目迁入spring boot框架时,会报错。

原因是我们业务写好了连接池,但spring boot在jar包存在的时候会主动加载spring boot的autoconfiguration创建连接池,但我们并未配置Spring Boot参数,也不需要配置。

1. mongodb

mongodb自动配置错误如下:

org.mongodb.driver.cluster               : Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
Caused by: java.net.ConnectException: Connection refused (Connection refused)

但是我没有引入spring-boot-starter-data-mongodb的jar包,后来发现我引入了spring-data-mongodb的jar

检查spring-boot-starter-data-mongodb的jar,包括3部分,如下:

我的jar包都有,相当于这些jar拼装成了 spring-boot-starter-data-mongodb

在Spring Boot中自动引入了自动配置功能

需要手动排除自动配置的数据源,在SpringBootApplication中exclude

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

启动不再报错连接localhost:27017,业务正常。

原理见Spring Boot官方文档

https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html#using-boot-disabling-specific-auto-configuration

2. mybatis

mybatis同理

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded data

***************************
APPLICATION FAILED TO START
***************************
 
Description:
 
Cannot determine embedded database driver class for database type NONE
 
Action:
 
If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

需要排除

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

3. 原理讲解

原理是EnableAutoConfiguration

进一步跟踪:

AutoConfigurationImportSelector这个类有自动加载与排除的逻辑

public String[] selectImports(AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return NO_IMPORTS;
		}
		AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
				.loadMetadata(this.beanClassLoader);
		AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata,
				annotationMetadata);
		return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
	}

注意加载代码

getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
/**
	 * Return the {@link AutoConfigurationEntry} based on the {@link AnnotationMetadata}
	 * of the importing {@link Configuration @Configuration} class.
	 * @param autoConfigurationMetadata the auto-configuration metadata
	 * @param annotationMetadata the annotation metadata of the configuration class
	 * @return the auto-configurations that should be imported
	 */
	protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
			AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return EMPTY_ENTRY;
		}
		AnnotationAttributes attributes = getAttributes(annotationMetadata);
		List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
		configurations = removeDuplicates(configurations);
		Set<String> exclusions = getExclusions(annotationMetadata, attributes);
		checkExcludedClasses(configurations, exclusions);
		configurations.removeAll(exclusions);
		configurations = filter(configurations, autoConfigurationMetadata);
		fireAutoConfigurationImportEvents(configurations, exclusions);
		return new AutoConfigurationEntry(configurations, exclusions);
	}

里面

getExclusions(annotationMetadata, attributes);
/**
	 * Return any exclusions that limit the candidate configurations.
	 * @param metadata the source metadata
	 * @param attributes the {@link #getAttributes(AnnotationMetadata) annotation
	 * attributes}
	 * @return exclusions or an empty set
	 */
	protected Set<String> getExclusions(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		Set<String> excluded = new LinkedHashSet<>();
		excluded.addAll(asList(attributes, "exclude"));
		excluded.addAll(Arrays.asList(attributes.getStringArray("excludeName")));
		excluded.addAll(getExcludeAutoConfigurationsProperty());
		return excluded;
	}

看到了,exclude或者excludeName,当然还有一种方法

private List<String> getExcludeAutoConfigurationsProperty() {
		if (getEnvironment() instanceof ConfigurableEnvironment) {
			Binder binder = Binder.get(getEnvironment());
			return binder.bind(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class).map(Arrays::asList)
					.orElse(Collections.emptyList());
		}
		String[] excludes = getEnvironment().getProperty(PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE, String[].class);
		return (excludes != null) ? Arrays.asList(excludes) : Collections.emptyList();
	}

通过application.properties文件配置spring.autoconfigure.exclude

private static final String PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";

总结

出现这种错误多半发生在引入了spring-boot-starter-mongodb等这样的starter插件jar,没有配置数据源url;或者旧业务升级spring boot(笔者就是这种情况)

解决方法:

不需要的jar不要引入即可解决问题

使用exclude排除,有三种实现方式exclude、excludeName、spring.autoconfigure.exclude

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java自旋锁及自旋的好处详解

    Java自旋锁及自旋的好处详解

    这篇文章主要介绍了Java自旋锁及自旋的好处详解,自旋就是自己在这里不停地循环,直到目标达成,而不像普通的锁那样,如果获取不到锁就进入阻塞,需要的朋友可以参考下
    2023-10-10
  • Java日期时间字符串和毫秒相互转换的方法

    Java日期时间字符串和毫秒相互转换的方法

    这篇文章主要为大家详细介绍了Java日期时间字符串和毫秒相互转换的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-12-12
  • Springboot接收POST请求,数据为json类型问题

    Springboot接收POST请求,数据为json类型问题

    在使用Spring框架中,当处理POST请求且内容为JSON类型时,应使用@RequestBody注解而非@RequestParam,通过@RequestBody可以将JSON数据绑定到一个Map对象中,然后通过Map的get方法来获取需要的参数
    2022-10-10
  • springboot如何通过URL方式访问外部资源

    springboot如何通过URL方式访问外部资源

    这篇文章主要介绍了springboot如何通过URL方式访问外部资源,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • Netty分布式Server启动流程服务端初始化源码分析

    Netty分布式Server启动流程服务端初始化源码分析

    本章主要讲解server启动的关键步骤, 读者只需要了解server启动的大概逻辑, 知道关键的步骤在哪个类执行即可, 并不需要了解每一步的运作机制, 之后会对每个模块进行深度分析
    2022-03-03
  • SpringCloud微服务网关限流方式

    SpringCloud微服务网关限流方式

    这篇文章主要介绍了SpringCloud微服务网关限流方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-08-08
  • 一篇文章教你使用枚举来实现java单例模式

    一篇文章教你使用枚举来实现java单例模式

    本篇文章主要介绍了Java实现单例的3种普遍的模式,饿汉式、懒汉式、枚举式。具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能给你带来帮助
    2021-07-07
  • java多线程并发executorservice(任务调度)类

    java多线程并发executorservice(任务调度)类

    这篇文章主要介绍了线程并发ScheduledExecutorService类,设置 ScheduledExecutorService ,2秒后,在 1 分钟内每 10 秒钟蜂鸣一次
    2014-01-01
  • 在Java8中构建Stream流的多种方式详解

    在Java8中构建Stream流的多种方式详解

    当我们处理集合数据时,往往需要对其进行各种操作,如过滤、映射、排序、归约等,在 Java 8 中引入的 Stream 流为我们提供了一种更加简洁和灵活的方式来处理数据,本文将介绍如何基于 Stream 构建流,为你展示创建和操作流的多种方法
    2023-08-08
  • SpringBoot参数校验的方法总结

    SpringBoot参数校验的方法总结

    今天带大家学习SpringBoot参数校验的方法,文中有非常详细的代码示例,对正在学习java的小伙伴们有很好地帮助,需要的朋友可以参考下
    2021-05-05

最新评论