Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between putting @Autowired to a variable and a method?

Tags:

java

spring

Class A {

   private B instanceB;

   @Autowired
   public setInstanceB(B instanceB) {
     this.instanceB = instanceB;
   }

}

Above one versus this one.

Class A {

   @Autowired
   private B instanceB;

   public setInstanceB(B instanceB) {
     this.instanceB = instanceB;
   }

}

Will the behavior differ based on the access modifier ?

like image 303
Maniganda Prakash Avatar asked Nov 02 '09 08:11

Maniganda Prakash


People also ask

Which Autowiring is better in Spring?

It is the default autowiring mode. It means no autowiring bydefault. The byName mode injects the object dependency according to name of the bean. In such case, property name and bean name must be same.

What are different types of Autowire?

The XML-configuration-based autowiring functionality has five modes – no , byName , byType , constructor , and autodetect .

What is the difference between Autowiring and dependency injection?

You can annotate fields and constructor using @Autowired to tell Spring framework to find dependencies for you. The @Inject annotation also serves the same purpose, but the main difference between them is that @Inject is a standard annotation for dependency injection and @Autowired is spring specific.

Why do we use @autowired annotation?

The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.


1 Answers

The difference is the setter will be called if that's where you put it, which is useful if it does other useful stuff, validation, etc. Usually you're comparing:

public class A {
  private B instanceB;

  @Autowired
  public setInstanceB(B instanceB) {
    this.instanceB = instanceB;
  }
}

vs

public class A {
  @Autowired
  private B instanceB;
}

(ie there is no setter).

The first is preferable in this situation because lack of a setter makes mocking/unit testing more difficult. Even if you have a setter but autowire the data member you can create a problem if the setter does something different. This would invalidate your unit testing.

like image 180
cletus Avatar answered Oct 24 '22 19:10

cletus