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() {
// 测试内容
}
}总结
@springbootapplication的exclude属性:用于排除特定的自动配置类,而不是用于排除主配置类本身。- 不同的配置类:可以创建不同的配置类,并在不同的环境中使用不同的配置类。
@testconfiguration:用于创建测试专用的配置类,并在测试中使用。
到此这篇关于@springbootconfiguration重复加载报错的文章就介绍到这了,更多相关@springbootconfiguration重复加载内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论