如何在@SpringBootTest中导入外部jar包的applicationContext.xml和Bean
第一步:调整测试类注解,导入外部资源
在你的MyTest测试类上补充两个注解:
- 导入XML配置:用
@ImportResource指定外部jar中applicationContext.xml的classpath路径 - 扫描外部jar的Service:要么用
@SpringBootTest的scanBasePackages属性指定MyService所在的包路径,要么用@Import(MyService.class)直接导入单个类
修改后的测试类示例:
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ImportResource; import org.springframework.beans.factory.annotation.Autowired; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; // 替换scanBasePackages为你外部jar中MyService所在的实际包路径 @SpringBootTest(scanBasePackages = "com.external.service.package") // 替换为外部jar中xml的实际classpath路径,有冲突可加classpath*:前缀扫描所有jar @ImportResource("classpath:applicationContext.xml") public class MyTest { // 注入待验证的MyService Bean @Autowired private MyService myService; @Test public void testMyServiceBeanCreated() { // 断言不为空即证明Bean创建成功 assertNotNull(myService); // 可选:验证配置参数是否正确加载,比如调用myService的配置取值方法做断言 } }
注意事项
- 如果XML存放在外部jar的META-INF目录下,路径写为
classpath:META-INF/applicationContext.xml - 存在同名XML文件冲突时,用
classpath*:applicationContext.xml强制加载所有jar下匹配的配置 - 不需要扫描整个外部包的话,可以删掉
scanBasePackages配置,新增@Import(MyService.class)注解直接导入单个Service类
内容的提问来源于stack exchange,提问作者Yuri Molodyko
相关产品推荐
相关产品推荐

