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() . These examples are extracted from open source projects. 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 Project: qconfig   File: QConfigPropertyAnnotationUtil.java    License: 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 Project: das   File: DasTransactionalEnabler.java    License: 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 3
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
@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 5
/**
 * 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 6
/**
 * 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 7
Source Project: turbo-rpc   File: TurboClientStarter.java    License: 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 8
Source Project: pacbot   File: RefreshScopeConfig.java    License: 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 9
Source Project: pacbot   File: RefreshScopeConfig.java    License: 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 10
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 11
@Override
protected String buildDefaultBeanName(BeanDefinition definition) {
	String beanClassName = definition.getBeanClassName();
	Assert.state(beanClassName != null, "No bean class name set");
	return beanClassName;
}
 
Example 12
Source Project: dal   File: DalTransactionalEnabler.java    License: 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 13
Source Project: pinpoint   File: TargetBeanFilter.java    License: 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 14
@Override
protected String buildDefaultBeanName(BeanDefinition definition) {
	String beanClassName = definition.getBeanClassName();
	Assert.state(beanClassName != null, "No bean class name set");
	return beanClassName;
}
 
Example 15
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
    return definition.getBeanClassName();
}
 
Example 16
/**
 * 处理服务提供者注解
 *
 * @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 17
private Class<?> resolveClass(BeanDefinition beanDefinition) {

        String beanClassName = beanDefinition.getBeanClassName();

        return resolveClassName(beanClassName, classLoader);

    }
 
Example 18
/**
 * 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 19
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 20
/**
 * 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);
}