您好,欢迎来到欧得旅游网。
搜索
您的当前位置:首页4、SpringBoot 关闭某个特定的配置类

4、SpringBoot 关闭某个特定的配置类

来源:欧得旅游网

分析

使用注解可以让SpringBoot根据当前应用项目所依赖的jar自动配置项目的相关配置,如下:

如果开发者不需要SpingBoot的某一项,该如何实现呢?可以在注解上进行关闭特定的自动配置,比如关闭:数据源

用途

如果未来你看到springboot中自己提供starter 提供几十个上百个配置类,如果有一些看着不爽,我想自己去写,怎么办呢?

  • 你可以覆盖它
  • 你可以先排除它,然后自己写。

举例子

面试题:如果在springBoot项目中,我们如何把官方提供好的配置类,排除掉?比如:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.2</version>
</dependency>

上面的依赖是mybatis依赖,默认情况myabtis的依赖,是一定要初始化一个数据源

<bean id="dataSource" class="druid|c3p0"></bean>
<bean id="sqlSessionFactory" class="SqlSessionFactoryBean">
    <propertity name="dataSource" ref="dataSource"/>
 </bean>

这也就为什么,如果项目直接依赖了mybatis, 直接启动就报错原因:

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

解决方案:排除数据源依赖:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

总结

  • 在开发,如果你依赖一个starter,你肯定是要去使用配置信息。如果你不使用就不要去依赖。
  • (exclude = {DataSourceAutoConfiguration.class}) 去排除掉,但是不建议。
  • 如果你一旦用了(exclude = {DataSourceAutoConfiguration.class})就说明你肯定要覆盖,或者你想要重写它。你就选择剔除。
  • exclude 真正作用就是:看着不官方提供不爽,我想自己造轮子。

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- ovod.cn 版权所有 湘ICP备2023023988号-4

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务