我一直在互联网上阅读涉及 Spring 的文章和教程,我发现其中很多都有代码示例,其中声明了其 @Autowired 成员的作用域 default 而不是私有(private)。
例如
@Autowired
AccountRepository accountRepository;
而不是
@Autowired
private AccountRepository accountRepository;
我想知道这是为什么。因为从好的封装的角度来看我认为这是错误的。在 Spring 中这样做有什么我不知道的好处吗?
最佳答案
直接通过字段注入(inject)依赖项从来不是一个好习惯,而是使用构造函数注入(inject)(@JBNizet也指出了这一点),你可以看看here了解更多详细信息。
简而言之,您应该在 bean 构造函数上使用 @Autowired
,该构造函数通常是 public
。
关于java - @Autowired 类成员声明为 <default> 范围而不是私有(private)的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43168417/