下面列出了org.springframework.beans.factory.BeanFactoryUtils#beanNamesForTypeIncludingAncestors ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Register all handlers found in the current ApplicationContext.
* <p>The actual URL determination for a handler is up to the concrete
* {@link #determineUrlsForHandler(String)} implementation. A bean for
* which no such URLs could be determined is simply not considered a handler.
* @throws org.springframework.beans.BeansException if the handler couldn't be registered
* @see #determineUrlsForHandler(String)
*/
protected void detectHandlers() throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Looking for URL mappings in application context: " + getApplicationContext());
}
String[] beanNames = (this.detectHandlersInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
getApplicationContext().getBeanNamesForType(Object.class));
// Take any bean name that we can determine URLs for.
for (String beanName : beanNames) {
String[] urls = determineUrlsForHandler(beanName);
if (!ObjectUtils.isEmpty(urls)) {
// URL paths found: Let's consider it a handler.
registerHandler(urls, beanName);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Rejected bean name '" + beanName + "': no URL paths identified");
}
}
}
}
/**
* Register all handlers found in the current ApplicationContext.
* <p>The actual URL determination for a handler is up to the concrete
* {@link #determineUrlsForHandler(String)} implementation. A bean for
* which no such URLs could be determined is simply not considered a handler.
* @throws org.springframework.beans.BeansException if the handler couldn't be registered
* @see #determineUrlsForHandler(String)
*/
protected void detectHandlers() throws BeansException {
ApplicationContext applicationContext = obtainApplicationContext();
String[] beanNames = (this.detectHandlersInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, Object.class) :
applicationContext.getBeanNamesForType(Object.class));
// Take any bean name that we can determine URLs for.
for (String beanName : beanNames) {
String[] urls = determineUrlsForHandler(beanName);
if (!ObjectUtils.isEmpty(urls)) {
// URL paths found: Let's consider it a handler.
registerHandler(urls, beanName);
}
}
if ((logger.isDebugEnabled() && !getHandlerMap().isEmpty()) || logger.isTraceEnabled()) {
logger.debug("Detected " + getHandlerMap().size() + " mappings in " + formatMappingName());
}
}
/**
* Find an EntityManagerFactory with the given name in the given
* Spring application context (represented as ListableBeanFactory).
* <p>The specified unit name will be matched against the configured
* persistence unit, provided that a discovered EntityManagerFactory
* implements the {@link EntityManagerFactoryInfo} interface. If not,
* the persistence unit name will be matched against the Spring bean name,
* assuming that the EntityManagerFactory bean names follow that convention.
* <p>If no unit name has been given, this method will search for a default
* EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}.
* @param beanFactory the ListableBeanFactory to search
* @param unitName the name of the persistence unit (may be {@code null} or empty,
* in which case a single bean of type EntityManagerFactory will be searched for)
* @return the EntityManagerFactory
* @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
* @see EntityManagerFactoryInfo#getPersistenceUnitName()
*/
public static EntityManagerFactory findEntityManagerFactory(
ListableBeanFactory beanFactory, String unitName) throws NoSuchBeanDefinitionException {
Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
if (StringUtils.hasLength(unitName)) {
// See whether we can find an EntityManagerFactory with matching persistence unit name.
String[] candidateNames =
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, EntityManagerFactory.class);
for (String candidateName : candidateNames) {
EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName);
if (emf instanceof EntityManagerFactoryInfo) {
if (unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) {
return emf;
}
}
}
// No matching persistence unit found - simply take the EntityManagerFactory
// with the persistence unit name as bean name (by convention).
return beanFactory.getBean(unitName, EntityManagerFactory.class);
}
else {
// Find unique EntityManagerFactory bean in the context, falling back to parent contexts.
return beanFactory.getBean(EntityManagerFactory.class);
}
}
/**
* Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier
* (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier).
* @param bf the factory 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})
*/
private static <T> T qualifiedBeanOfType(ListableBeanFactory bf, Class<T> beanType, String qualifier) {
String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
String matchingBean = null;
for (String beanName : candidateBeans) {
if (isQualifierMatch(qualifier::equals, beanName, bf)) {
if (matchingBean != null) {
throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName);
}
matchingBean = beanName;
}
}
if (matchingBean != null) {
return bf.getBean(matchingBean, beanType);
}
else if (bf.containsBean(qualifier)) {
// Fallback: target bean at least found by bean name - probably a manually registered singleton.
return bf.getBean(qualifier, beanType);
}
else {
throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
" bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!");
}
}
/**
* Find a single default EntityManagerFactory in the Spring application context.
* @return the default EntityManagerFactory
* @throws NoSuchBeanDefinitionException if there is no single EntityManagerFactory in the context
*/
protected EntityManagerFactory findDefaultEntityManagerFactory(String requestingBeanName)
throws NoSuchBeanDefinitionException {
String[] beanNames =
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, EntityManagerFactory.class);
if (beanNames.length == 1) {
String unitName = beanNames[0];
EntityManagerFactory emf = (EntityManagerFactory) this.beanFactory.getBean(unitName);
if (this.beanFactory instanceof ConfigurableBeanFactory) {
((ConfigurableBeanFactory) this.beanFactory).registerDependentBean(unitName, requestingBeanName);
}
return emf;
}
else if (beanNames.length > 1) {
throw new NoUniqueBeanDefinitionException(EntityManagerFactory.class, beanNames);
}
else {
throw new NoSuchBeanDefinitionException(EntityManagerFactory.class);
}
}
private NamespaceContextBuilder lookupNamespaceContextBuilder() {
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, NamespaceContextBuilder.class);
if (beanNames.length > 0) {
if (beanNames.length > 1) {
log.warn("Expected to find 1 beans of type {} but found instead {} ({})",
beanNames.length,
NamespaceContextBuilder.class.getCanonicalName(),
beanNames
);
}
log.debug("Using NamespaceContextBuilder - {}", beanNames[0]);
return applicationContext.getBean(beanNames[0], NamespaceContextBuilder.class);
} else {
log.debug("Using NamespaceContextBuilder - default");
return new NamespaceContextBuilder();
}
}
/**
* Find an EntityManagerFactory with the given name in the given
* Spring application context (represented as ListableBeanFactory).
* <p>The specified unit name will be matched against the configured
* persistence unit, provided that a discovered EntityManagerFactory
* implements the {@link EntityManagerFactoryInfo} interface. If not,
* the persistence unit name will be matched against the Spring bean name,
* assuming that the EntityManagerFactory bean names follow that convention.
* <p>If no unit name has been given, this method will search for a default
* EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}.
* @param beanFactory the ListableBeanFactory to search
* @param unitName the name of the persistence unit (may be {@code null} or empty,
* in which case a single bean of type EntityManagerFactory will be searched for)
* @return the EntityManagerFactory
* @throws NoSuchBeanDefinitionException if there is no such EntityManagerFactory in the context
* @see EntityManagerFactoryInfo#getPersistenceUnitName()
*/
public static EntityManagerFactory findEntityManagerFactory(
ListableBeanFactory beanFactory, String unitName) throws NoSuchBeanDefinitionException {
Assert.notNull(beanFactory, "ListableBeanFactory must not be null");
if (StringUtils.hasLength(unitName)) {
// See whether we can find an EntityManagerFactory with matching persistence unit name.
String[] candidateNames =
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, EntityManagerFactory.class);
for (String candidateName : candidateNames) {
EntityManagerFactory emf = (EntityManagerFactory) beanFactory.getBean(candidateName);
if (emf instanceof EntityManagerFactoryInfo) {
if (unitName.equals(((EntityManagerFactoryInfo) emf).getPersistenceUnitName())) {
return emf;
}
}
}
// No matching persistence unit found - simply take the EntityManagerFactory
// with the persistence unit name as bean name (by convention).
return beanFactory.getBean(unitName, EntityManagerFactory.class);
}
else {
// Find unique EntityManagerFactory bean in the context, falling back to parent contexts.
return beanFactory.getBean(EntityManagerFactory.class);
}
}
/**
* Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier
* (e.g. {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier).
* @param bf the factory 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})
*/
private static <T> T qualifiedBeanOfType(ListableBeanFactory bf, Class<T> beanType, String qualifier) {
String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
String matchingBean = null;
for (String beanName : candidateBeans) {
if (isQualifierMatch(qualifier::equals, beanName, bf)) {
if (matchingBean != null) {
throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName);
}
matchingBean = beanName;
}
}
if (matchingBean != null) {
return bf.getBean(matchingBean, beanType);
}
else if (bf.containsBean(qualifier)) {
// Fallback: target bean at least found by bean name - probably a manually registered singleton.
return bf.getBean(qualifier, beanType);
}
else {
throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
" bean found for qualifier '" + qualifier + "' - neither qualifier match nor bean name match!");
}
}
@Override
public void afterPropertiesSet() throws Exception {
if (operationMapperManager == null) {
operationMapperManager = new OperationMapperManager();
operationMapperManager.setEntityMapperManager(new EntityMapperManager());
}
if (dialect == null) {
// 将来可能扩展点:不同的DAO可以有不同的Dialect哦,而且是自动知道,不需要外部设置。
dialect = new MySQLDialect();
}
//
if (logger.isInfoEnabled()) {
String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(//
applicationContext, GenericDAO.class);
logger.info("[jade-plugin-sql] found " + beanNames.length + " GenericDAOs: "
+ Arrays.toString(beanNames));
}
}
/**
* Given a type of EnvironmentRepository (git, svn, native, etc...) returns the name
* of the factory bean. See {@link #getCompositeTypeList(Environment)}
* @param type type of a repository
* @param beanFactory Spring Bean Factory
* @return name of the factory bean
*/
public static String getFactoryName(String type,
ConfigurableListableBeanFactory beanFactory) {
String[] factoryNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
beanFactory, EnvironmentRepositoryFactory.class, true, false);
return Arrays.stream(factoryNames).filter(n -> n.startsWith(type)).findFirst()
.orElse(null);
}
public static <T extends Annotation, F> List<F> findAnnotatedBeans(Class<T> annotationType, Class<F> elementType) {
List<F> beans = new ArrayList<>();
for (String name : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, Object.class)) {
if (applicationContext.findAnnotationOnBean(name, annotationType) != null) {
beans.add(applicationContext.getBean(name, elementType));
}
}
return beans;
}
private String getBeanNameFor(ListableBeanFactory beanFactory, Class<?> type) {
String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
beanFactory, type, false, false);
Assert.state(names.length == 1, "No unique MessageBus (found " + names.length
+ ": " + Arrays.asList(names) + ")");
return names[0];
}
/**
* Retrieve all 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 factory to get the target beans from (also searching ancestors)
* @param beanType the type of beans to retrieve
* @param qualifier the qualifier for selecting among all type matches
* @return the matching beans of type {@code T}
* @throws BeansException if any of the matching beans could not be created
* @since 5.1.1
* @see BeanFactoryUtils#beansOfTypeIncludingAncestors(ListableBeanFactory, Class)
*/
public static <T> Map<String, T> qualifiedBeansOfType(
ListableBeanFactory beanFactory, Class<T> beanType, String qualifier) throws BeansException {
String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, beanType);
Map<String, T> result = new LinkedHashMap<>(4);
for (String beanName : candidateBeans) {
if (isQualifierMatch(qualifier::equals, beanName, beanFactory)) {
result.put(beanName, beanFactory.getBean(beanName, beanType));
}
}
return result;
}
private void assertOneMessageSourceOnly(ClassPathXmlApplicationContext ctx, Object myMessageSource) {
String[] beanNamesForType = ctx.getBeanNamesForType(StaticMessageSource.class);
assertEquals(1, beanNamesForType.length);
assertEquals("myMessageSource", beanNamesForType[0]);
beanNamesForType = ctx.getBeanNamesForType(StaticMessageSource.class, true, true);
assertEquals(1, beanNamesForType.length);
assertEquals("myMessageSource", beanNamesForType[0]);
beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, StaticMessageSource.class);
assertEquals(1, beanNamesForType.length);
assertEquals("myMessageSource", beanNamesForType[0]);
beanNamesForType = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, StaticMessageSource.class, true, true);
assertEquals(1, beanNamesForType.length);
assertEquals("myMessageSource", beanNamesForType[0]);
Map<?, StaticMessageSource> beansOfType = ctx.getBeansOfType(StaticMessageSource.class);
assertEquals(1, beansOfType.size());
assertSame(myMessageSource, beansOfType.values().iterator().next());
beansOfType = ctx.getBeansOfType(StaticMessageSource.class, true, true);
assertEquals(1, beansOfType.size());
assertSame(myMessageSource, beansOfType.values().iterator().next());
beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, StaticMessageSource.class);
assertEquals(1, beansOfType.size());
assertSame(myMessageSource, beansOfType.values().iterator().next());
beansOfType = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, StaticMessageSource.class, true, true);
assertEquals(1, beansOfType.size());
assertSame(myMessageSource, beansOfType.values().iterator().next());
}
public <T> T getInstance(String name, Class<T> type) {
AnnotationConfigApplicationContext context = getContext(name);
if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context,
type).length > 0) {
return context.getBean(type);
}
return null;
}
/**
* Find the names of beans annotated with
* {@linkplain ControllerAdvice @ControllerAdvice} in the given
* ApplicationContext and wrap them as {@code ControllerAdviceBean} instances.
*/
public static List<ControllerAdviceBean> findAnnotatedBeans(ApplicationContext applicationContext) {
List<ControllerAdviceBean> beans = new ArrayList<ControllerAdviceBean>();
for (String name : BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, Object.class)) {
if (applicationContext.findAnnotationOnBean(name, ControllerAdvice.class) != null) {
beans.add(new ControllerAdviceBean(name, applicationContext));
}
}
return beans;
}
public <T> Map<String, T> getInstances(String name, Class<T> type) {
AnnotationConfigApplicationContext context = getContext(name);
if (BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context,
type).length > 0) {
return BeanFactoryUtils.beansOfTypeIncludingAncestors(context, type);
}
return null;
}
@SuppressWarnings("unchecked")
private static List<CassandraFactoryCustomizer<? super EmbeddedCassandraFactory>> getCustomizers(
ConfigurableApplicationContext context) {
List<CassandraFactoryCustomizer<? super EmbeddedCassandraFactory>> customizers = new ArrayList<>();
String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context,
ResolvableType.forType(new CassandraFactoryCustomizerTypeReference()));
for (String name : names) {
customizers.add((CassandraFactoryCustomizer<? super EmbeddedCassandraFactory>) context.getBean(name));
}
AnnotationAwareOrderComparator.sort(customizers);
return customizers;
}
private String[] getBeanNamesForTypedStream(ResolvableType requiredType) {
return BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this, requiredType);
}
/**
* Find all eligible Advisor beans in the current bean factory,
* ignoring FactoryBeans and excluding beans that are currently in creation.
* @return the list of {@link org.springframework.aop.Advisor} beans
* @see #isEligibleBean
*/
public List<Advisor> findAdvisorBeans() {
// Determine list of advisor bean names, if not cached already.
String[] advisorNames = this.cachedAdvisorBeanNames;
if (advisorNames == null) {
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the auto-proxy creator apply to them!
advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Advisor.class, true, false);
this.cachedAdvisorBeanNames = advisorNames;
}
if (advisorNames.length == 0) {
return new ArrayList<>();
}
List<Advisor> advisors = new ArrayList<>();
for (String name : advisorNames) {
if (isEligibleBean(name)) {
if (this.beanFactory.isCurrentlyInCreation(name)) {
if (logger.isTraceEnabled()) {
logger.trace("Skipping currently created advisor '" + name + "'");
}
}
else {
try {
advisors.add(this.beanFactory.getBean(name, Advisor.class));
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException) {
BeanCreationException bce = (BeanCreationException) rootCause;
String bceBeanName = bce.getBeanName();
if (bceBeanName != null && this.beanFactory.isCurrentlyInCreation(bceBeanName)) {
if (logger.isTraceEnabled()) {
logger.trace("Skipping advisor '" + name +
"' with dependency on currently created bean: " + ex.getMessage());
}
// Ignore: indicates a reference back to the bean we're trying to advise.
// We want to find advisors other than the currently created bean itself.
continue;
}
}
throw ex;
}
}
}
}
return advisors;
}