I have a service. I want to autowire a policy bean in my service.
@Service
class MyService {
@Autowired
Policy myPolicy;
}
The policy is an interface. It has 3 subclass.
interface Policy {
void method();
}
class APolicy implements Policy...
class BPolicy implements Policy...
class CPolicy implements Policy...
There is a condition to initialize the policy class.
if (config.isA()) {
myPolicy = new APolicy();
} else if (config.isB()) {
myPolicy = new BPolicy();
} else {
myPolicy = new CPolicy();
}
I want to autowired myPolicy. so I write the condition code.
class ACondition extends SpringBootConditoin {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
if (config.isA()) {
return new ConditionOutcome(true, "ok");
} else {
return new ConditionOutcome(false, "error");
}
}
}
class BCondition extends SpringBootConditoin {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
if (config.isB()) {
return new ConditionOutcome(true, "ok");
} else {
return new ConditionOutcome(false, "error");
}
}
}
class CCondition extends SpringBootConditoin {
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
if (config.isC()) {
return new ConditionOutcome(true, "ok");
} else {
return new ConditionOutcome(false, "error");
}
}
}
@Service
@Conditional(ACondition.class)
class APolicy implements Policy...
@Service
@Conditional(BCondition.class)
class BPolicy implements Policy...
@Service
@Conditional(CCondition.class)
class CPolicy implements Policy...
Just one policy implementation will be initialize. Others will be ignored. but MyService can't autowired the matched policy. It shows there are 3 bean instance but don't know witch will be autowired.
so how can I autowire the matched bean without the word "new" and "if...else"?