Java Code Examples for org.springframework.beans.factory.config.BeanDefinition#getBeanClassName()

The following examples show how to use org.springframework.beans.factory.config.BeanDefinition#getBeanClassName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QConfigPropertyAnnotationUtil.java    From qconfig with MIT License 6 votes vote down vote up
private static Class<?> getClassByBeanDefinitionName(ConfigurableListableBeanFactory beanFactory, String beanDefinitionName, ClassLoader beanClassLoader) {
    if (Strings.isNullOrEmpty(beanDefinitionName)) return null;

    BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);
    if (beanDefinition == null) return null;

    if (beanDefinition instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDefinition).hasBeanClass()) {
        return ((AbstractBeanDefinition) beanDefinition).getBeanClass();
    }

    String className = beanDefinition.getBeanClassName();
    if (!Strings.isNullOrEmpty(className) && beanClassLoader != null) {
        try {
            return beanClassLoader.loadClass(className);
        } catch (ClassNotFoundException e) {
            logger.debug("找不到类: {}", className, e);
        }
    }
    return null;
}
 
Example 2
Source File: DataDictionaryConfigurationTest.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
protected void somethingShouldHaveParentBeans( Class<?> baseClass, List<String> exclusions ) throws Exception {
    Field f = dataDictionary.getClass().getDeclaredField("ddBeans");
    f.setAccessible(true);
    KualiDefaultListableBeanFactory ddBeans = (KualiDefaultListableBeanFactory)f.get(dataDictionary);
    List<String> failingBeanNames = new ArrayList<String>();

    for ( String beanName : ddBeans.getBeanDefinitionNames() ) {
        if ( doesBeanNameMatchList(beanName, exclusions)) {
            continue ;
        }
        BeanDefinition beanDef = ddBeans.getMergedBeanDefinition(beanName);
        String beanClass = beanDef.getBeanClassName();
        if ( beanClass == null ) {
            System.err.println( "ERROR: Bean " + beanName + " has a null class." );
        }
        if ( !beanDef.isAbstract()
                && beanClass != null
                && baseClass.isAssignableFrom(Class.forName(beanClass) ) ) {
            try {
                BeanDefinition parentBean = ddBeans.getBeanDefinition(beanName + "-parentBean");
            } catch ( NoSuchBeanDefinitionException ex ) {
                failingBeanNames.add(beanName + " : " + beanDef.getResourceDescription() +"\n");
            }
        }
    }
    assertEquals( "The following " + baseClass.getSimpleName() + " beans do not have \"-parentBean\"s:\n" + failingBeanNames, 0, failingBeanNames.size() );
}
 
Example 3
Source File: TeiidBeanDefinitionPostProcessor.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
private boolean isMatch(BeanDefinition beanDefinition, String beanName) {
    String className = beanDefinition.getBeanClassName();
    if (className == null) {
        if (beanDefinition.getFactoryMethodName() != null &&
                beanDefinition.getFactoryMethodName().contentEquals(beanName)) {
            Object source = beanDefinition.getSource();
            if (source instanceof MethodMetadata) {
                String returnType = ((MethodMetadata) source).getReturnTypeName();
                if (returnType.contentEquals("javax.sql.DataSource")) {
                    return true;
                }
                if (returnType.startsWith("org.springframework") || returnType.startsWith("io.micrometer")
                        || returnType.startsWith("com.fasterxml.") || returnType.startsWith("org.hibernate.")) {
                    return false;
                }
                className = returnType;
            }
        }
    }

    if (className != null) {
        try {
            final Class<?> beanClass = Class.forName(className);
            if (DataSource.class.isAssignableFrom(beanClass)
                    || BaseConnectionFactory.class.isAssignableFrom(beanClass)) {
                return true;
            }
        } catch (ClassNotFoundException e) {
        }
    }
    return false;
}
 
Example 4
Source File: RefreshScopeConfig.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Overriding to update the test scope. 
 * 
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) {
    for (String beanName : factory.getBeanDefinitionNames()) {
        BeanDefinition beanDef = factory.getBeanDefinition(beanName);
        if (beanDef.getBeanClassName() != null && beanDef.getBeanClassName().startsWith("com.tmobile.pacman")) {
            beanDef.setScope("refresh");
        }
    }
}
 
Example 5
Source File: LoggingContextLoader.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void componentRegistered(ComponentDefinition componentDefinition) {
	log.info("Registered component [" + componentDefinition.getName() + "]");
	for (BeanDefinition bd : componentDefinition.getBeanDefinitions()) {
		String name = bd.getBeanClassName();
		if (bd instanceof BeanComponentDefinition) {
			name = ((BeanComponentDefinition) bd).getBeanName();
		}
		log.info("Registered bean definition: [" + name + "]" + " from " + bd.getResourceDescription());
	}
}
 
Example 6
Source File: SpringCamelContextBootstrap.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
/**
 * Gets JNDI names for all configured instances of {@link JndiObjectFactoryBean}
 *
 * Note: If this method is invoked before ApplicationContext.refresh() then any bean property
 * values containing property placeholders will not be resolved.
 *
 * @return the unmodifiable list of JNDI binding names
 */
public List<String> getJndiNames() {
    List<String> bindings = new ArrayList<>();
    for(String beanName : applicationContext.getBeanDefinitionNames()) {
        BeanDefinition definition = applicationContext.getBeanDefinition(beanName);
        String beanClassName = definition.getBeanClassName();

        if (beanClassName != null && beanClassName.equals(JndiObjectFactoryBean.class.getName())) {
            MutablePropertyValues propertyValues = definition.getPropertyValues();
            Object jndiPropertyValue = propertyValues.get("jndiName");

            if (jndiPropertyValue == null) {
                LOGGER.debug("Skipping JNDI binding dependency for bean: {}", beanName);
                continue;
            }

            String jndiName = null;
            if (jndiPropertyValue instanceof String) {
                jndiName = (String) jndiPropertyValue;
            } else if (jndiPropertyValue instanceof TypedStringValue) {
                jndiName = ((TypedStringValue) jndiPropertyValue).getValue();
            } else {
                LOGGER.debug("Ignoring unknown JndiObjectFactoryBean property value type {}", jndiPropertyValue.getClass().getSimpleName());
            }

            if (jndiName != null) {
                bindings.add(jndiName);
            }
        }
    }
    return Collections.unmodifiableList(bindings);
}
 
Example 7
Source File: CachingListenerValidatorImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Resolves class of a beanDefinition
 * @param beanDefinition the bean definition
 * @return class of the bean definition
 * @throws IllegalStateException if the given bean definition class can not
 * be resolved
 * @see org.springframework.beans.factory.config.BeanDefinition#setBeanClassName(String)
 * @see org.springframework.beans.factory.support.AbstractBeanDefinition#resolveBeanClass(ClassLoader)
 */
protected Class resolveBeanClass(BeanDefinition beanDefinition)
		throws IllegalStateException {
	try {
		return ((AbstractBeanDefinition) beanDefinition)
				.resolveBeanClass(ClassUtils.getDefaultClassLoader());
	} catch (ClassNotFoundException e) {
		throw new IllegalStateException("Could not resolve class ["
				+ beanDefinition.getBeanClassName() + "] of caching listener");
	}
}
 
Example 8
Source File: DasTransactionalEnabler.java    From das with Apache License 2.0 5 votes vote down vote up
private void replaceBeanDefinition() {
    for(String beanName: getBeanDefinitionNames()) {
        BeanDefinition beanDef = getBeanDefinition(beanName);
        String beanClassName = beanDef.getBeanClassName();

        if(beanClassName == null || beanClassName.equals(BEAN_FACTORY_NAME) || isSpringSmartClassLoader(beanDef)) {
            continue;
        }

        Class beanClass;
        try {
            beanClass = Class.forName(beanDef.getBeanClassName());
        } catch (ClassNotFoundException e) {
            throw new BeanDefinitionValidationException("Cannot validate bean: " + beanName, e);
        }

        boolean annotated = false;
        for (Method method : beanClass.getMethods()) {
            if(isTransactionAnnotated(method)) {
                annotated = true;
                break;
            }
        }

        if(!annotated) {
            continue;
        }

        beanDef.setBeanClassName(BEAN_FACTORY_NAME);
        beanDef.setFactoryMethodName(FACTORY_METHOD_NAME);

        ConstructorArgumentValues cav = beanDef.getConstructorArgumentValues();

        if(cav.getArgumentCount() != 0) {
            throw new BeanDefinitionValidationException("The transactional bean can only be instantiated with default constructor.");
        }

        cav.addGenericArgumentValue(beanClass.getName());
    }
}
 
Example 9
Source File: RefreshScopeConfig.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
        throws BeansException {
    for (String beanName : factory.getBeanDefinitionNames()) {
        BeanDefinition beanDef = factory.getBeanDefinition(beanName);
        if (beanDef.getBeanClassName() != null
                && beanDef.getBeanClassName().startsWith(
                        "com.tmobile.pacman")) {
            beanDef.setScope("refresh");
        }
    }
}
 
Example 10
Source File: TurboClientStarter.java    From turbo-rpc with Apache License 2.0 5 votes vote down vote up
private Collection<Class<?>> extractTurboServiceClassList(ConfigurableListableBeanFactory beanFactory) {
	LocalDateTime startTime = LocalDateTime.now();
	Set<Class<?>> turboServiceSet = new HashSet<>();
	String[] beanNames = beanFactory.getBeanDefinitionNames();

	for (int i = 0; i < beanNames.length; i++) {
		String beanName = beanNames[i];
		BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
		String beanClassName = beanDefinition.getBeanClassName();

		extractTurboServiceClass(turboServiceSet, beanClassName);
	}

	if (logger.isInfoEnabled()) {
		LocalDateTime finishTime = LocalDateTime.now();
		Duration duration = Duration.between(startTime, finishTime);

		String turboServiceString = turboServiceSet//
				.stream()//
				.map(clazz -> clazz.getName())//
				.collect(Collectors.joining(",", "[", "]"));

		logger.info("扫描到TurboService: " + turboServiceString);
		logger.info("扫描TurboService耗时: " + duration);
	}

	return turboServiceSet;
}
 
Example 11
Source File: TargetBeanFilter.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
public boolean isTarget(final SpringBeansTargetScope scope, final String beanName, final BeanDefinition beanDefinition) {
    if (scope == null || beanName == null || beanDefinition == null) {
        return false;
    }

    final String className = beanDefinition.getBeanClassName();
    if (className == null) {
        return false;
    }

    if (cache.contains(className)) {
        return false;
    }

    for (SpringBeansTarget target : targets) {
        // check scope.
        if (target.getScope() != scope) {
            continue;
        }

        boolean condition = false;
        // check base packages.
        final List<String> basePackages = target.getBasePackages();
        if (CollectionUtils.hasLength(basePackages)) {
            if (!isBasePackage(target, className)) {
                continue;
            }
            condition = true;
        }

        // check bean name pattern.
        final List<PathMatcher> namePatterns = target.getNamePatterns();
        if (CollectionUtils.hasLength(namePatterns)) {
            if (!isBeanNameTarget(target, beanName)) {
                continue;
            }
            condition = true;
        }

        // check class name pattern.
        final List<PathMatcher> classPatterns = target.getClassPatterns();
        if (CollectionUtils.hasLength(classPatterns)) {
            if (!isClassNameTarget(target, className)) {
                continue;
            }
            condition = true;
        }

        // check class annotation.
        final List<String> annotations = target.getAnnotations();
        if (CollectionUtils.hasLength(annotations)) {
            if (!(beanDefinition instanceof AnnotatedBeanDefinition) || !isAnnotationTarget(target, (AnnotatedBeanDefinition) beanDefinition)) {
                continue;
            }
            condition = true;
        }

        if (condition) {
            // AND condition.
            return true;
        }
    }

    return false;
}
 
Example 12
Source File: RpcDefinitionPostProcessor.java    From joyrpc with Apache License 2.0 4 votes vote down vote up
/**
 * 处理服务提供者注解
 *
 * @param definition bean定义
 * @param registry   注册中心
 */
protected void processProviderAnnotation(final BeanDefinition definition, BeanDefinitionRegistry registry) {
    String className = definition.getBeanClassName();
    if (isEmpty(className)) {
        return;
    }
    Class<?> providerClass = resolveClassName(className, classLoader);
    //查找服务提供者注解
    Class<?> targetClass = providerClass;
    Pair<AnnotationProvider<Annotation, Annotation>, Annotation> pair = null;
    while (targetClass != null && targetClass != Object.class) {
        pair = getProviderAnnotation(targetClass);
        if (pair != null) {
            break;
        }
        targetClass = targetClass.getSuperclass();
    }
    if (pair != null) {
        ProviderBean<?> provider = pair.getKey().toProviderBean(pair.getValue(), environment);
        //获取接口类名
        Class<?> interfaceClazz = provider.getInterfaceClass(() -> getInterfaceClass(providerClass));
        if (interfaceClazz == null) {
            //没有找到接口
            throw new BeanInitializationException("there is not any interface in class " + providerClass);
        }
        //获取服务实现类的Bean名称
        String refName = getComponentName(providerClass);
        if (refName == null) {
            refName = Introspector.decapitalize(getShortName(providerClass.getName()));
            //注册服务实现对象
            if (!registry.containsBeanDefinition(refName)) {
                registry.registerBeanDefinition(refName, definition);
            }
        }
        if (isEmpty(provider.getId())) {
            provider.setId(PROVIDER_PREFIX + refName);
        }
        //添加provider
        addProvider(provider, interfaceClazz, refName);
    }
}
 
Example 13
Source File: CustomBeanNameGenerator.java    From SO with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
    return definition.getBeanClassName();
}
 
Example 14
Source File: ConfigurationClassPostProcessor.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected String buildDefaultBeanName(BeanDefinition definition) {
	String beanClassName = definition.getBeanClassName();
	Assert.state(beanClassName != null, "No bean class name set");
	return beanClassName;
}
 
Example 15
Source File: DalTransactionalEnabler.java    From dal with Apache License 2.0 4 votes vote down vote up
private void replaceBeanDefinition() {
    for (String beanName : getBeanDefinitionNames()) {
        BeanDefinition beanDef = getBeanDefinition(beanName);
        String beanClassName = beanDef.getBeanClassName();

        if (beanClassName == null || beanClassName.equals(BEAN_FACTORY_NAME))
            continue;

        Class beanClass;
        try {
            beanClass = Class.forName(beanDef.getBeanClassName());
        } catch (ClassNotFoundException e) {
            throw new BeanDefinitionValidationException("Cannot validate bean: " + beanName, e);
        }

        boolean annotated = false;

        List<Method> methods = new ArrayList<>();
        ReflectUtils.addAllMethods(beanClass, methods);
        List<Method> unsupportedMethods = new ArrayList<>();

        for (int i = 0; i < methods.size(); i++) {
            Method currentMethod = methods.get(i);

            if (isTransactionAnnotated(currentMethod)) {
                if (Modifier.isFinal(currentMethod.getModifiers()) || Modifier.isStatic(currentMethod.getModifiers()) || Modifier.isPrivate(currentMethod.getModifiers()))
                    unsupportedMethods.add(currentMethod);
                annotated = true;
            }
        }

        if (!unsupportedMethods.isEmpty()){
            StringBuilder errMsg=new StringBuilder();
            errMsg.append(String.format("The Methods below are not supported in dal transaction due to private, final or static modifier, please use public,protected or default modifier instead:"));
            errMsg.append("\n");
            int index=1;
            for (Method method : unsupportedMethods) {
                errMsg.append(String.format("%d. %s", index, method.toString()));
                errMsg.append("\n");
                index++;
            }
            throw new DalRuntimeException(errMsg.toString());
        }

        if (!annotated)
            continue;

        beanDef.setBeanClassName(BEAN_FACTORY_NAME);
        beanDef.setFactoryMethodName(FACTORY_METHOD_NAME);

        ConstructorArgumentValues cav = beanDef.getConstructorArgumentValues();

        if (cav.getArgumentCount() != 0)
            throw new BeanDefinitionValidationException("The transactional bean can only be instantiated with default constructor.");

        cav.addGenericArgumentValue(beanClass.getName());
    }
}
 
Example 16
Source File: ConfigurationClassPostProcessor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
protected String buildDefaultBeanName(BeanDefinition definition) {
	String beanClassName = definition.getBeanClassName();
	Assert.state(beanClassName != null, "No bean class name set");
	return beanClassName;
}
 
Example 17
Source File: AnnotationBeanNameGenerator.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Derive a default bean name from the given bean definition.
 * <p>The default implementation simply builds a decapitalized version
 * of the short class name: e.g. "mypackage.MyJdbcDao" -> "myJdbcDao".
 * <p>Note that inner classes will thus have names of the form
 * "outerClassName.InnerClassName", which because of the period in the
 * name may be an issue if you are autowiring by name.
 * @param definition the bean definition to build a bean name for
 * @return the default bean name (never {@code null})
 */
protected String buildDefaultBeanName(BeanDefinition definition) {
	String beanClassName = definition.getBeanClassName();
	Assert.state(beanClassName != null, "No bean class name set");
	String shortClassName = ClassUtils.getShortName(beanClassName);
	return Introspector.decapitalize(shortClassName);
}
 
Example 18
Source File: BeanUtils.java    From spring-context-support with Apache License 2.0 3 votes vote down vote up
private static Class<?> resolveBeanType(ConfigurableListableBeanFactory beanFactory, BeanDefinition beanDefinition) {

        String factoryBeanName = beanDefinition.getFactoryBeanName();

        ClassLoader classLoader = beanFactory.getBeanClassLoader();

        Class<?> beanType = null;

        if (StringUtils.hasText(factoryBeanName)) {

            beanType = getFactoryBeanType(beanFactory, beanDefinition);

        }

        if (beanType == null) {

            String beanClassName = beanDefinition.getBeanClassName();

            if (StringUtils.hasText(beanClassName)) {

                beanType = resolveBeanType(beanClassName, classLoader);

            }

        }

        if (beanType == null) {

            if (logger.isErrorEnabled()) {

                String message = beanDefinition + " can't be resolved bean type!";

                logger.error(message);
            }

        }

        return beanType;

    }
 
Example 19
Source File: AnnotationBeanNameGenerator.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Derive a default bean name from the given bean definition.
 * <p>The default implementation simply builds a decapitalized version
 * of the short class name: e.g. "mypackage.MyJdbcDao" -> "myJdbcDao".
 * <p>Note that inner classes will thus have names of the form
 * "outerClassName.InnerClassName", which because of the period in the
 * name may be an issue if you are autowiring by name.
 * @param definition the bean definition to build a bean name for
 * @return the default bean name (never {@code null})
 */
protected String buildDefaultBeanName(BeanDefinition definition) {
	String beanClassName = definition.getBeanClassName();
	Assert.state(beanClassName != null, "No bean class name set");
	String shortClassName = ClassUtils.getShortName(beanClassName);
	return Introspector.decapitalize(shortClassName);
}
 
Example 20
Source File: ServiceAnnotationBeanPostProcessor.java    From dubbo-2.6.5 with Apache License 2.0 3 votes vote down vote up
private Class<?> resolveClass(BeanDefinition beanDefinition) {

        String beanClassName = beanDefinition.getBeanClassName();

        return resolveClassName(beanClassName, classLoader);

    }