@SpringBootConfiguration重复加载报错

Junit单元测试@Test启动报错,@SpringBootConfiguration注解重复问题排查:

@SpringBootApplication 注解的 exclude 属性用于排除特定的自动配置类,而不是用于排除主配置类本身。因此,不能通过 exclude 属性来排除主配置类的加载。

正确的使用方式

如果你想排除某些自动配置类,可以使用 exclude 属性。例如:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class PortalApplication {
    public static void main(String[] args) {
        SpringApplication.run(PortalApplication.class, args);
    }
}

排除主配置类的加载

如果你确实需要在某些情况下排除主配置类的加载,可以考虑以下几种方法:

1. 使用不同的配置类

你可以创建不同的配置类,并在不同的环境中使用不同的配置类。例如,可以创建一个测试配置类,并在测试中使用它。

// 主配置类
@SpringBootApplication
public class PortalApplication {
    public static void main(String[] args) {
        SpringApplication.run(PortalApplication.class, args);
    }
}

// 测试配置类
@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

在测试类中使用 @SpringBootTest 注解来指定测试配置类:

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.junit.runner.RunWith;
import org.junit.Test;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class)
public class PortalApplicationTest {
    @Test
    public void contextLoads() {
        // 测试内容
    }
}
2. 使用 @TestConfiguration

如果你只需要在测试中排除某些配置,可以使用 @TestConfiguration 注解来创建测试专用的配置类。

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;

@TestConfiguration
public class TestConfig {
    @Bean
    public SomeBean someBean() {
        return new SomeBean();
    }
}

在测试类中使用 @Import 注解来导入测试配置类:

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.context.annotation.Import;
import org.junit.runner.RunWith;
import org.junit.Test;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = PortalApplication.class)
@Import(TestConfig.class)
public class PortalApplicationTest {
    @Test
    public void contextLoads() {
        // 测试内容
    }
}

总结

  • @SpringBootApplicationexclude 属性:用于排除特定的自动配置类,而不是用于排除主配置类本身。
  • 不同的配置类:可以创建不同的配置类,并在不同的环境中使用不同的配置类。
  • @TestConfiguration:用于创建测试专用的配置类,并在测试中使用。
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你这个代码我看不懂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值