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

分析

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

在这里插入图片描述

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

用途

如果未来你看到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})

提示:但是关闭数据源不推荐,既然你在开发中引入了mybatis为什么又不配置数据源呢?除非你自己去定义数据源。你可以这样做,否则不建议

总结

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值