@autowired vs新密钥?

编程入门 行业动态 更新时间:2024-10-22 08:17:37
本文介绍了@autowired vs新密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用@Autowired批注和new键有什么区别? 让我们在一个类中:

What is the difference using @Autowired annotation and new key ? Let's within a class what would be the difference between :

@Autowired private UserDao userdao;

private UserDao userDao = new UserDaoImpl();

对性能有影响吗?

推荐答案

除了其他人已经提到的低耦合之外,主要区别在于,使用new方法,您每次都会得到一个新对象,无论您是否愿意.即使UserDaoImpl是可重用的,无状态的和线程安全的(DAO类应努力做到),您仍将在需要它们的每个位置创建它们的新实例.

Besides low coupling, that others have already touched on, a major difference is that with the new approach, you get a new object every time, whether you want to or not. Even if UserDaoImpl is reusable, stateless and threadsafe (which DAO classes should strive to be) you will still create new instances of them at every place they are needed.

开始时这可能不是一个大问题,但是请考虑随着对象图的增长-UserDaoImpl可能需要一个Hibernate会话,它需要一个DataSource,它需要一个JDBC连接-它很快就变成了很多对象必须一遍又一遍地创建和初始化.当您在代码中依赖new时,您还将在整个地方扩展初始化逻辑.像本示例一样,您需要在UserDaoImpl中包含代码以使用适当的参数打开JDBC连接,但是所有其他DAO类都必须执行相同的操作.

This may not be a huge issue at first, but consider as the object graph grows - the UserDaoImpl perhaps needs a Hibernate session, which needs a DataSource, which needs a JDBC connection - it quickly becomes a lot of objects that has to be created and initialized over and over again. When you rely on new in your code, you are also spreading out initialization logic over a whole bunch of places. Like in this example, you need to have code in your UserDaoImpl to open a JDBC connection with the proper parameters, but all other DAO classes have to do the same thing.

这是控制反转(IoC)出现的地方.它旨在通过将对象创建和生命周期与对象绑定和使用分离开来解决这些问题. IoC的最基本应用是简单的Factory类.一种更复杂的方法是依赖注入,例如Spring.

And here is where Inversion-of-Control (IoC) comes in. It aims to address just these things, by decoupling object creation and life-cycle from object binding and usage. The most basic application of IoC is a simple Factory class. A more sophisticated approach is Dependency Injection, such as Spring.

对效果有影响吗?

是的,但是很可能不会很重要.使用Springs依赖注入在启动时会花费更多,因为必须初始化容器并设置所有托管对象.但是,由于您将不会创建托管对象的新实例(假设这是您设计它们的方式),因此,通过减少GC负载和减少对象创建,您将获得一些运行时性能.

Yes, but it's most likely not going to be very significant. Using Springs dependency injection costs a little more in startup-time as the container has to be initialized and all managed objects set up. However, since you won't be creating new instances of your managed objects (assuming that is how you design them), you'll gain some runtime performance from less GC load and less object creation.

但是,您最大的收获将是应用程序的可维护性和健壮性.

Your big gain however is going to be in maintainability and robustness of your application.

更多推荐

@autowired vs新密钥?

本文发布于:2023-11-15 22:39:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598586.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密钥   autowired

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!