You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring构造器注入(Constructor Autowired)问题及正确实现方案

构造器注入替代字段注入的问题解决

问题背景

我原本通过字段注入实现功能,代码如下:

@Component
public class ZMyServiceConstructor {

   @Autowired
   private RestTemplate restTemplate;

    @Value("${my_test_property}")
    private String url;

}

尝试改用构造器注入时遇到了两个问题:

  • 不定义任何构造方法,或使用@NoArgsConstructor、@RequiredArgsConstructor注解时,url能正常读取配置值,但restTemplate为null,对应代码示例:
@Component
//@NoArgsConstructor 
//@RequiredArgsConstructor
public class ZMyServiceConstructor {

   private RestTemplate restTemplate;

    @Value("${my_test_property}")
    private String url;

}
  • 使用@AllArgsConstructor注解时,直接抛出错误:
required a bean of type 'java.lang.String' that could not be found

解决方案

通过以下方式可以解决问题:

  1. 给restTemplate字段添加final修饰符,Lombok的@RequiredArgsConstructor会自动生成仅包含该final字段的构造方法
  2. @Value修饰的url字段不能加final,因为字段注入的逻辑是在构造方法执行后才完成的

正确代码示例

@Component
@RequiredArgsConstructor
public class ZMyServiceConstructor {

    private final RestTemplate restTemplate;

    @Value("${my_test_property}")
    private String url;

}

这段代码等价于手动编写构造器注入的实现:

@Component
public class ZMyServiceConstructor {

    private final RestTemplate restTemplate;

    @Value("${my_test_property}")
    private String url;

    @Autowired
    public ZMyServiceConstructor(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
}

内容的提问来源于stack exchange,提问作者Abe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:31:18