Java - Spring - @Autowired @Resource @Inject (Wiring Types) - @Qualifier @Named

Java - Spring - @Autowired @Resource @Inject (Wiring Types) - @Qualifier @Named

@Qualifier vs @Named

@Qualifier@Named

belong to both Spring and Java extension package:

  • @javax.inject.Qualifier
  • @org.springframework.beans.factory.annotation.Qualifier
belong to Java

@Autowired vs @Resource vs @Inject

@Autowired@Resource@Inject
  1. Match by Type
  2. Match by Qualifier
  3. Match by Name
  1. Match by Name
  2. Match by Type
  3. Match by Qualifier
  1. Match by Type
  2. Match by Qualifier
  3. Match by Name

supports injecting:

  • fields
  • setter methods
  • constructors
  • multi-argument methods

supports injecting:

  • fields
  • setter methods

belongs to Spring

  • @org.springframework.beans.factory.annotation.Autowired

belong to the Java extension package:

  • @javax.annotation.Resource

belong to the Java extension package:

  • @javax.inject.Inject

Which To Use

Scenario@Resource@Inject@Autowired
Application-wide use of singletons through polymorphism
Fine-grained application behavior configuration through polymorphism
Dependency injection should be handled solely by the Jakarta EE platform
Dependency injection should be handled solely by the Spring Framework

Example Use

@Bean
@Qualifier("appContext1")
public com.context.AppContext appContext1() {
	return new AppContext();
}


@Qualifier("appContext2")
public com.context.AppContext appContext2() {
	return new AppContext();
}

given the configuration above, the following shows what's allowed and not:

// type case
@Autowired
AppContext appContext;  // ERROR

// qualifier case
@Autowired
@Qualifier("appContext1")
AppContext appContext;  // NO ERROR

// named case
@Autowired
AppContext appContext1; // NO ERROR