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
解决方案
通过以下方式可以解决问题:
- 给
restTemplate字段添加final修饰符,Lombok的@RequiredArgsConstructor会自动生成仅包含该final字段的构造方法 @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
相关产品推荐
相关产品推荐

