java - 如何以编程方式获取带有类和限定符的 bean?

标签 java spring applicationcontext

有可能@Autowired bean 类和@Qualifier在 Spring 。

如何以编程方式做同样的事情? IE。为 bean 提供类和限定符的搜索上下文?

我看到很多 getBean()方法,它们都没有明确声称它可以做这件事。

最佳答案

您可以使用 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;

我认为这正是您所需要的。

关于java - 如何以编程方式获取带有类和限定符的 bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37943409/

相关文章:

Java:使用参数类型的子类实现Setter方法?

java - 如何从 gradle 中的 eclipse .classpath 读取依赖项?

spring - 在Spring Boot中使用@CrossOrigin

Spring上下文层次结构

java - Spring 应用程序上下文加密

Java - 将字符串拆分为具有字符限制的句子

java - 如何结束 if 并移至另一行

java - 在 Spring ajax 方法中返回带有对象的消息供 java 脚本读取

java - Spring MVC : How to read and change a @PathVariable value

java - 从 Jar 中加载上下文