如何不用@SpringBootTest,用@SpringJUnitConfig自动注入包私有实现的JwtService
解决方案
方法一:通过组件扫描自动发现包私有Bean
创建测试专用的Spring配置类,利用@ComponentScan扫描目标库的包,让Spring自动识别并注册包私有的JwtServiceImpl:
// 测试配置类,放在你的测试代码包下 package com.your.test.package import org.springframework.context.annotation.ComponentScan import org.springframework.context.annotation.Configuration @Configuration @ComponentScan(basePackages = ["com.jwt.accesstoken"]) class JwtServiceTestConfig
修改测试类,将@SpringJUnitConfig指向这个配置类:
@SpringJUnitConfig(JwtServiceTestConfig::class) @ActiveProfiles("it-test") class JwtServiceGeneratorTest { @Autowired private lateinit var jwtService: JwtService // 可正常注入 // ... 测试逻辑 }
原理:Spring的@ComponentScan会扫描指定包下所有带有@Component注解的类,哪怕类是包私有,Spring通过反射机制可以访问并实例化这些类,完成Bean注册。
方法二:手动通过反射注册Bean
如果不想扫描整个包(避免引入多余Bean),可以在配置类中通过反射手动创建JwtServiceImpl实例并注册为Bean:
@Configuration class JwtServiceTestConfig { @Bean fun jwtService(): JwtService { // 反射获取包私有类 val implClass = Class.forName("com.jwt.accesstoken.JwtServiceImpl") // 获取构造方法(如果构造方法是包私有,需开启可访问性) val constructor = implClass.getDeclaredConstructor() constructor.isAccessible = true // 创建实例并转为接口类型 return constructor.newInstance() as JwtService } }
同样将测试类的@SpringJUnitConfig指向该配置类即可完成注入。
内容的提问来源于stack exchange,提问作者firstpostcommenter
相关产品推荐
相关产品推荐

