How to get @Qualifier from each bean of @Autowired List<> in Spring

Viewed 1767

Is there any way to get @Qualifier name from each bean of @Autowired List<Bean> in Spring. Or more broadly: Can i get a Bean @Qualifier information at runtime if i have a bean instance?

Lets suppose i have:

//Config.java
@Bean(name = "en-db")
@ConfigurationProperties(prefix = "spring.datasource.en")
public DataSource dataSourceEN() {...}

@Bean(name = "de-db")
@ConfigurationProperties(prefix = "spring.datasource.de")
public DataSource dataSourceDE() {...}

//Repository.java
public Repository(List<DataSource> ds) { 
    // Is there any way to create a hashmap of Qualifier => Bean? 
    // like {"en-db" : ds.get(0), "de-db" : ds.get(1)}
    // or maybe there is a way to autowire the Hashmap<Qualifier, Bean>
}

right now i'm using this (and it works fine):

public Repository(@Qualifier("en-db") DataSource en, 
                  @Qualifier("de-db") DataSource de, //... and many more  
){ 
   Map<String, EntityManager> dataSources = new HashMap<>();
   dataSources.put("en-db", en);
   dataSources.put("de-db", de);
   ...

}

But i have 10+ data sources and it feels that there should be some way to detect the Bean Qualifier even after autowire and i can just use @Autowired List.

PS: it is not a localisation issue, i'm using all 10 db on a single page

1 Answers

To get a bean 's most detailed metadata information , your best bet is to inject DefaultListableBeanFactory and play around its API .

But your case (i.e Get a map for certain type of bean keyed by its beanName) can be simply achieved by injecting ApplicationContext and call its getBeansOfType:

@Autowired
public Repository(ApplicationContext ctx) { 
   //The key is the beanName which is en-db , de-db .....  
   Map<String, DataSource> map = ctx.getBeansOfType(DataSource.class);
}

Or better yet is to inject Map<String, DataSource> :

public class Repository {

   @Autowired
   private Map<String, DataSource> dataSources;

}
Related