为什么建议用“构造函数注入“替换@Autowired?

@Autowired字段注入(Field Injection)通常不被推荐,因为它使得类对具体的实现产生依赖,降低了可测试性,并且在一些场景下可能引起循环依赖问题。

而且视觉上编辑器上的感叹号数量看着真的很难受!!!!!!


平时写代码我还是推荐使用构造函数注入(Constructor Injection)或方法注入(Setter Injection)来代替字段注入。这有助于更好地管理类的依赖关系,并提高代码的可维护性和可测试性。

下面是一个使用构造函数注入的例子:

 private final ThingRepository thingRepository;
    private final ProductRepository productRepository;
    private final ThingModelRepository thingModelRepository;
    private final ThingDataRepository thingDataRepository;
    private final RocketMQTemplate rocketMQTemplate;

    @Autowired
    public ThingUtils(
            ThingRepository thingRepository,
            ProductRepository productRepository,
            ThingModelRepository thingModelRepository,
            ThingDataRepository thingDataRepository,
            RocketMQTemplate rocketMQTemplate) {
        this.thingRepository = thingRepository;
        this.productRepository = productRepository;
        this.thingModelRepository = thingModelRepository;
        this.thingDataRepository = thingDataRepository;
        this.rocketMQTemplate = rocketMQTemplate;
    }

构造函数注入了 ThingUtils 所需的所有依赖项。这样的注入方式提高了类的可测试性,并使得类的依赖关系更加明确。

你可能感兴趣的:(java,开发语言)