3

Can Spring autowire variables of a class based on the Qualifier which was used to autowire the class enclosing those variables?

Say, I have a common ToolsSet class

public class ToolsSet {
  @AutoWired Drill drill;
  @AutoWired Hammer hammer;
}

@Qualifier("IndustrialTools")
public class IndustrialHammer implements Hammer {} 
@Qualifier("IndustrialTools")   
public class IndustrialDrill implements Drill {} 

@Qualifier("HomeTools")  
public class HomeHammer implements Hammer{}
@Qualifier("HomeTools")
public class HomeDrill implements Drill{}

Different jobs need different toolsets,

public class JobA {

  @AutoWired
  @Qualifier("HomeTools")
  ToolsSet toolsSet;

}

public class JobB {

  @AutoWired
  @Qualifier("IndustrialTools")
  ToolsSet toolsSet;

}

Is it possible to autowire the variables of the ToolsSet class based on the Qualifier used to autowire the Jobs class?

Edit: I know that I can always write a @Configuration class, and define beans for different qualifiers. I just want to skip the configuration class. What I would like to have is to use the Qualifier once, in the Job class and automagically autowire the Drill and Hammer classes using the same qualifier which was used to autowire the ToolsSet class.

Rnet
  • 4,796
  • 9
  • 47
  • 83
  • 2
    Look at this answer: http://stackoverflow.com/questions/19414734/understanding-spring-autowired-usage/19419296#19419296. It explains exactly how to do it. – Avi Feb 11 '16 at 20:43
  • Just autowire by name, instead of by type – fps Feb 11 '16 at 20:57
  • @Avi It explains basics of Autowiring. My question is how do you 'pass-on' the qualifier to the ToolsSet class. I understand that I can always write a Configuration class and manually build the toolsSet classes for different qualifiers, which I don't want to do. – Rnet Feb 11 '16 at 21:04
  • 1
    I understand now better what you're trying to do. I can't answer a full answer at the moment but I will answer once I get to a computer. – Avi Feb 11 '16 at 21:23
  • 1
    BTW - great question – Avi Feb 11 '16 at 21:45

0 Answers0