简体   繁体   English

在 spring 引导中自动装配的 class 上自动装配和使用新关键字之间的区别?

[英]Difference between autowired and using new keyword on autowired class in spring boot?

@Autowired
private EmployeeService employeeService;

vs对比

@Autowired
private EmployeeService employeeService = new EmployeeService();

Is using new EmployeeService() on autowired class different than just using new EmployeeService() ?在自动接线的 class 上使用new EmployeeService()与仅使用new EmployeeService()不同吗?

If a bean for @Autowired is injected it will override your created object.如果注入@Autowired的 bean,它将覆盖您创建的 object。 But if there is no bean created you have a fallback (in this case new EmployeeService() . That might be helpful for tests but it's kind of an anti-pattern because normally you just want one of both behaviours.但是,如果没有创建 bean,则您有一个后备(在这种情况下为new EmployeeService() 。这可能对测试有帮助,但它是一种反模式,因为通常您只想要两种行为之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM