Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

benefit of @Autowired annotation in Java

Maybe, because of my wrong English, I couldn't understand the benefit of using @Autowired annotation.

According to the tutorial we can simplify the first(I.) case to second case(II.) by means of @Autowired.

My question is, what is the meaning of the @Autowired ? Because it doesnt tell any more, since without using @Autowired the compiler can figure out that "EmpDao emDao" and "EmpManager" are closely related according the declaration.

code cited from here

I.

    <bean id="empDao" class="EmpDao" />
    <bean id="empManager" class="EmpManager">
       <property name="empDao" ref="empDao" />
    </bean>

public class EmpManager {

   private EmpDao empDao;

   public EmpDao getEmpDao() {
      return empDao;
   }

   public void setEmpDao(EmpDao empDao) {
      this.empDao = empDao;
   }

   ...
}

II.

<context:annotation-config />

<bean id="empManager" class="autowiredexample.EmpManager" />
<bean id="empDao"     class="autowiredexample.EmpDao" />

import org.springframework.beans.factory.annotation.Autowired;

public class EmpManager {

   @Autowired
   private EmpDao empDao;

}
like image 555
cscsaba Avatar asked Feb 14 '11 22:02

cscsaba


2 Answers

When the server bootstraps itself. It finds

 <context:annotation-config />

in the application context and then goes through the classes defined in the contexts. If there are any beans that are autowired, it injects that into the class by referring the context file.

Basically, it promotes convention over configuration. That's what most frameworks do these days to reduce the development time.

like image 61
Vanchinathan Chandrasekaran Avatar answered Sep 18 '22 23:09

Vanchinathan Chandrasekaran


@Autowired is spring-specific. @Inject is the standard equivallent. It is an annotation that tells the context (spring, or in the case of @Inject - any DI framework) to try to set an object into that field.

The compiler has nothing to do with this - it is the DI framework (spring) that instantiates your objects at runtime, and then sets their dependencies at the points you have specified - either via XML or via an annotation.

I agree it is a possible scenario for a DI framework to try to inject dependencies into all fields, even if they are not annotated. (And if you want to exclude a particular field, to annotate it). But they chose the other strategy (configuration-over-convention). By the way:

  • if using xml config and choose some form of autowiring, the dependencies of the bean will be automatically autowired without the need to specify anything
  • you can specify per-context autowiring settings.
like image 25
Bozho Avatar answered Sep 22 '22 23:09

Bozho