小编Mar*_*r-Z的帖子

依赖注入 - 如何改进具有多个参数的构造函数

我是 Spring 的新手,最近注意到@Autowired不鼓励在类字段中使用。相反,建议使用构造函数进行依赖注入 (DI)。

问题是我定义了一个需要访问许多存储库的 bean。最初,该 bean 有几个自动装配的字段,保存对这些存储库的引用,但现在我只是删除了注释@Autowired并使用构造函数来初始化它们。结果是一个带有许多参数的构造函数,只要我创建更多存储库/服务,这些参数将来可能会增长:

@Bean
public Syncer syncer(SatBackendApplication.AppParamService appParamService,
                     CustomerRepository customerRepository,
                     AddressRepository addressRepository,
                     ContactPersonRepository contactPersonRepository,
                     CustomerContractRepository customerContractRepository,
                     ProductRepository productRepository,
                     OrderRepository orderRepository,
                     OrderRepository.OrderLineRepository orderLineRepository
                     ) {
    return new Syncer(
            appParamService,
            customerRepository,
            addressRepository,
            contactPersonRepository,
            customerContractRepository,
            productRepository,
            orderRepository,
            orderLineRepository);
}
Run Code Online (Sandbox Code Playgroud)

这是向 bean 注入依赖项的正确方法吗?有没有代码更少的替代解决方案?

java spring dependency-injection spring-boot

1
推荐指数
1
解决办法
162
查看次数

标签 统计

dependency-injection ×1

java ×1

spring ×1

spring-boot ×1