可以在Spring中使用@Autowired
bean和@Qualifier
。
如何以编程方式执行相同的操作?即bean的搜索上下文给它的类和它的限定符?
我看到了很多getBean()
方法,他们都没有明确声称它可以做到这一点。
答案 0 :(得分:5)
您可以使用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;
我认为这正是你所需要的。
答案 1 :(得分:1)
尝试this一个 -
applicationContext.getBeansOfType(MyType.class).get("bean-name")
答案 2 :(得分:0)
如果您希望Spring以编程方式处理@Autowired
字段/属性,则需要从AutowireCapableBeanFactory
获取ApplicationContext
个实例并致电factory.autowireBean(myClassInstanceWithBeansToAutowire);
。