简体   繁体   中英

Spring, configure preferred bean to autowire when multiple instances are present

I've an interface being injected as bean into multiple components.
Three classes implement this interface which leads to ambiguity for spring to autowire the beans.

I would like a flexible way (preferentially through the application.properties or an env var) to specify which bean to chose...

EX

public interface MyComponent{
}
@Component("a")
public class MyComponentA implements MyComponent{
}
@Component("b")
public class MyComponentB implements MyComponent {
}

@Component("c")
public class MyComponentC implements MyComponent{
}

then many classes through the system might autowire this component

@Autowired
MyComponent bean;

I know i can use @Qualifier("a") to determine which implementation to inject, but the problem is that if I want to cheange from 'a' to 'c' i will need to change the code in multiple places...

I wanted a global way to select which bean to use when qualifier is not present

I guess what you are looking for is the @ConditionalOnProperty annotation that you can apply to the component:

@Component("a")
@ConditionalOnProperty(name = "component", havingValue = "a")
public class MyComponentA implements MyComponent{
}

@Component("b")
@ConditionalOnProperty(name = "component", havingValue = "b")
public class MyComponentB implements MyComponent {
}

@Component("c")
@ConditionalOnProperty(name = "component", havingValue = "c")
public class MyComponentC implements MyComponent{
}

See https://www.baeldung.com/spring-conditionalonproperty for more information about this solution.

You can explore more about conditional annotations in Spring here: https://www.baeldung.com/spring-conditional-annotations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM