自动装配和在SpringBoot的自动装配类上使用new关键字的区别?

@Autowired
private EmployeeService employeeService;

对比

@Autowired
private EmployeeService employeeService = new EmployeeService();

使用new EmployeeService()上比只使用自动装配类不同new EmployeeService()

回答

如果@Autowired注入了一个 bean,它将覆盖您创建的对象。但是,如果没有创建 bean,您将有一个回退(在这种情况下new EmployeeService()。这可能对测试有所帮助,但它是一种反模式,因为通常您只想要两种行为中的一种。

  • I consider this an anti-pattern also for tests. Even in tests you want to know exactly what injected where, statements like that obscure the code.

以上是自动装配和在SpringBoot的自动装配类上使用new关键字的区别?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>