如何@autowired注入一个带有final属性的bean

@Service

public class Demo1Impl {

private final String name;

Demo1Impl(String name) {
    this.name = name;
}

public String getName(int i) {
        return "name";
}

}

单元测试要测试这个getName方法

@RunWith(SpringJUnit4ClassRunner.class)

@SpringBootTest(classes = DemoApplication.class)

class Demo1ImplTest {

@Autowired
Demo1Impl demo1;

@Test
void getName() {

    System.out.println(demo1.getName(1));
}

}

run后报错,显示找不到合格的bean,这是一个Springboot项目,单元测试的时候我该如何注入Demo1Impl呢?

因为 Spring 是利用无参数构造函数创造实例的,而代码中只有一个有参构造函数,所以注入时报错了。
建议:这个特殊的类,应该手动配置它的 Bean.xml 信息,使用有参构造函数进行注入。
参考这篇文章:https://blog.csdn.net/maty_wang/article/details/80335272