欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot中自动化配置的利弊以及解决方法

程序员文章站 2024-02-14 09:42:52
本文主要给大家介绍了关于spring boot自动化配置的利弊及解决方法的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍: spring boot...

本文主要给大家介绍了关于spring boot自动化配置的利弊及解决方法的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:

spring boot中的双刃剑:自动化配置

在之前的中,我们通过各种功能性示例体验了spring boot的自动化配置给我们所带来的超便利的新开发方式。但是,在一些情况下spring boot的自动化配置也会给我们惹来不少的麻烦,比如这些场景:

项目依赖复杂的情况下,由于依赖方的依赖组织不够严格,可能引入了一些实际我们不需要的依赖,从而导致我们的项目满足一些特定的自动化配置。

传统spring项目转换为spring boot项目的过程中,由于不同的组织方式问题,引发自动化配置加载的错误,比如:通过xml手工组织的多数据源配置等。

上面这些原因都会导致不必要的自动化配置加载而导致应用无法启动或触发/health的健康检查不通过等问题。比如,我们在改造传统spring项目到spring boot项目中碰到的一些错误:

六月 21, 2017 6:23:47 下午 org.apache.catalina.loader.webappclassloaderbase clearreferencesthreads
警告: the web application [root] appears to have started a thread named [abandoned connection cleanup thread] but has failed to stop it. this is very likely to create a memory leak. stack trace of thread:
 java.lang.object.wait(native method)
 java.lang.ref.referencequeue.remove(referencequeue.java:143)
 com.mysql.jdbc.abandonedconnectioncleanupthread.run(abandonedconnectioncleanupthread.java:43)
2017-06-21 18:23:47,230 info [main] org.springframework.boot.autoconfigure.logging.autoconfigurationreportlogginginitializer - 
error starting applicationcontext. to display the auto-configuration report re-run your application with 'debug' enabled.
2017-06-21 18:23:47,237 error [main] org.springframework.boot.diagnostics.loggingfailureanalysisreporter - 
***************************
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).

从报错信息中,我们就可以分析出错误原因是触发了数据源的自动化配置,然而当前项目其实并不需要数据源。查其根源是依赖方提供的api依赖中引用了一些多余的依赖触发了该自动化配置的加载。

如何解决

为了解决上面所述的问题,我们可以用两种方法来解决:

  • 通过外部依赖的修改来解决:通过与依赖方沟通,在对方提供的api依赖中去掉不必要的依赖
  • 通过禁用指定的自动化配置来避免加载不必要的自动化配置,下面列举了禁用的方法:

使用了@enableautoconfiguration的时候

@enableautoconfiguration(exclude={datasourceautoconfiguration.class})

使用了@springbootapplication的时候

@springbootapplication(exclude = {datasourceautoconfiguration.class})

使用了@springcloudapplication的时候

@enableautoconfiguration(exclude={datasourceautoconfiguration.class})
@springcloudapplication

通过配置文件来设置

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.datasourceautoconfiguration

总结

好了,大概就这样,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持