Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get bean with class and qualifier programmatically?

It is possible to @Autowired bean with class and @Qualifier in Spring.

How to do the same thing programmatically? I.e. search context for bean giving it's class and it's qualifier?

I see a plenty of getBean() methods, neither of them explicitly claims it can do the thing.

like image 862
Dims Avatar asked Jun 21 '16 11:06

Dims


2 Answers

You can use BeanFactoryAnnotationUtils.qualifiedBeanOfType(BeanFactory beanFactory, Class<T> beanType, String qualifier):

/**
     * Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a
     * qualifier (e.g. via {@code <qualifier>} or {@code @Qualifier}) matching the given
     * qualifier, or having a bean name matching the given qualifier.
     * @param beanFactory the BeanFactory to get the target bean from
     * @param beanType the type of bean to retrieve
     * @param qualifier the qualifier for selecting between multiple bean matches
     * @return the matching bean of type {@code T} (never {@code null})
     * @throws NoUniqueBeanDefinitionException if multiple matching beans of type {@code T} found
     * @throws NoSuchBeanDefinitionException if no matching bean of type {@code T} found
     * @throws BeansException if the bean could not be created
     * @see BeanFactory#getBean(Class)
     */
    public static <T> T qualifiedBeanOfType(BeanFactory beanFactory, Class<T> beanType, String qualifier)
            throws BeansException;

I think that it's exactly what you need.

like image 176
Dmitry Ovchinnikov Avatar answered Oct 12 '22 23:10

Dmitry Ovchinnikov


Try this one -

applicationContext.getBeansOfType(MyType.class).get("bean-name")
like image 35
shachar Avatar answered Oct 13 '22 00:10

shachar