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;
and
private UserDao userDao = new UserDaoImpl();
Is there an impact on the performance?
Besides low coupling, that others have already touched on, a major difference is that with the
newapproach, you get a new object every time, whether you want to or not. Even ifUserDaoImplis 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.This may not be a huge issue at first, but consider as the object graph grows – the
UserDaoImplperhaps 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 onnewin 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.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.
Is there an impact on the performance?
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.