Tuesday 24 November 2015

Difference Between @Resource, @Autowired and @Inject in Spring Injection


  1. @Resource – Defined in the javax.annotation package and part of Java
  2. @Inject – Defined in the javax.inject package and part of Java
  3. @Autowired – Defined in the package org.springframework.bean.factory and part of Spring framework.

@Autowired and Inject behaves exactly same

Order is  -> byType -> @Qualifier ->byName





@Service

public class FruitProcessor {

@Autowired
private Fruit fruit;
//private Fruit fruit;
//private Fruit fruit;
}

@Service
public class FruitProcessor {

@Resource
@Qualifier("mango")
private Fruit apple;
//private Fruit fruit;
//private Fruit fruit;

@Override
public String toString() {
return "FruitProcessor [apple=" + apple + "]";
}

}

output is :
FruitProcessor [apple=Apple [taste=sour, getColor()=null]]

Means still we mentioned @Qualifier("mango") but it is autowired by
byName

Because Autowiring  order for @Resource  is -byName -> byType->@Qualifier

Summary :-
@Autowired and @Inject
  1. Matches by Type
  2. Restricts by Qualifiers
  3. Matches by Name
@Resource
  1. Matches by Name
  2. Matches by Type
  3. Restricts by Qualifiers (ignored if match is found by name)

No comments:

Post a Comment