SpringBootTest环境下Lombok生成的构造器无法隐式自动注入问题
问题根因
你遇到的报错是因为JUnit 5默认自主实例化测试类,虽然你加了@SpringBootTest注解,但Lombok的@RequiredArgsConstructor生成的构造方法没有标注@Autowired,Spring无法识别需要为这个构造方法注入参数,JUnit找不到对应参数的解析器,就抛出了ParameterResolutionException异常。
解决方案
方案1(最优,保留构造注入最佳实践)
给@RequiredArgsConstructor添加配置,让Lombok生成的构造方法自动带上@Autowired注解,修改后的B类代码如下:
import lombok.RequiredArgsConstructor; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest @RequiredArgsConstructor(onConstructor_ = @Autowired) public class B { private final A a; @Test public void testB() { System.out.println("testB"); } }
方案2(手写构造方法)
不用Lombok生成构造器,手动写构造方法并添加@Autowired注解:
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class B { private final A a; @Autowired public B(A a) { this.a = a; } @Test public void testB() { System.out.println("testB"); } }
方案3(字段注入)
放弃构造注入,直接使用字段注入,移除@RequiredArgsConstructor和字段的final修饰:
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class B { @Autowired private A a; @Test public void testB() { System.out.println("testB"); } }
内容的提问来源于stack exchange,提问作者Pioneer Even
相关产品推荐
相关产品推荐

