Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring pick highest priority bean

Tags:

java

spring

With a config like this:

class MySpringConfig {
  @Bean // Lowest priority
  @Qualifier("pri1")
  Bean beanPri1() { ... }

  @Bean // Medium priority
  @Qualifier("pri2")
  Bean beanPri2() { ... }

//  @Bean // Highest priority
//  @Qualifier("pri3")
//  Bean beanPri3() { ... }
}

and a service like this:

@Service
class MyService {
  @Autowired
  @Qualifier("pri1")
  Bean beanPri1;

  @Autowired
  Bean beanWhateverTheHighestPriIs;
}

Is it possible to tell Spring to inject:

  • beanPri1 (since that was given by @Qualifier) into Service.beanPri1
  • Whatever the highest priority bean is into Service.beanWhateverTheHighestPriIs

using annotations or something similar that can be reused relatively easily across configurations and different bean sets?

Examples with the above configuration and doing the following changes:

  • No changes: Service.beanWhateverTheHighestPriIs should be beanPri2
  • Uncommenting beanPri3: Service.beanWhateverTheHighestPriIs should be beanPri3
  • Commenting beanPri2: Service.beanWhateverTheHighestPriIs should be beanPri1
like image 319
levant pied Avatar asked Aug 10 '26 00:08

levant pied


1 Answers

You can use @Order annotation to tell spring which to use first

like image 119
Nir Levy Avatar answered Aug 11 '26 13:08

Nir Levy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!