Example usage for org.springframework.beans.factory.config BeanDefinition getBeanClassName

List of usage examples for org.springframework.beans.factory.config BeanDefinition getBeanClassName

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config BeanDefinition getBeanClassName.

Prototype

@Nullable
String getBeanClassName();

Source Link

Document

Return the current bean class name of this bean definition.

Usage

From source file:com.liferay.arkadiko.bean.AKBeanPostProcessor.java

/**
 * Post process bean factory./*from   w  ww .ja  v a 2 s .co  m*/
 *
 * @param beanFactory the bean factory
 * @throws BeansException the beans exception
 */
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    if (!(beanFactory instanceof DefaultListableBeanFactory)) {
        return;
    }

    DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;

    defaultListableBeanFactory.setInstantiationStrategy(this);

    AutowireCandidateResolver autowireCandidateResolver = defaultListableBeanFactory
            .getAutowireCandidateResolver();

    defaultListableBeanFactory
            .setAutowireCandidateResolver(new AKAutowireCandidateResolver(autowireCandidateResolver));

    for (String beanName : defaultListableBeanFactory.getBeanDefinitionNames()) {

        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

        if (!(beanDefinition instanceof AbstractBeanDefinition)) {
            continue;
        }

        String className = beanDefinition.getBeanClassName();

        if (className == null) {
            continue;
        }

        try {
            AKBeanDefinition akBeanDefinition = new AKBeanDefinition(this,
                    (AbstractBeanDefinition) beanDefinition, beanName, getServiceRegistry());

            defaultListableBeanFactory.removeBeanDefinition(beanName);

            defaultListableBeanFactory.registerBeanDefinition(beanName, akBeanDefinition);
        } catch (Exception e) {
            if (_log.isLoggable(Level.SEVERE)) {
                _log.log(Level.SEVERE, e.getMessage(), e);
            }
        }
    }
}

From source file:com.cloudseal.spring.client.namespace.CloudSealBeanDefinitionParserInstance.java

private ManagedMap getBeanPropertyAsManagedMap(BeanDefinition bean, String propertyName) {
    PropertyValue property = bean.getPropertyValues().getPropertyValue(propertyName);
    String beanClassname = bean.getBeanClassName();
    if (property == null) {
        throw new IllegalStateException("No property " + propertyName + " in bean " + beanClassname);
    }/*from  w w  w  . j a  v a 2  s. c o m*/
    Object value = property.getValue();
    if (!ManagedMap.class.isInstance(value)) {
        throw new IllegalStateException("Property " + propertyName + " in bean " + beanClassname
                + " is not ManagedMap: " + value.getClass().getCanonicalName());
    }
    return (ManagedMap) value;
}

From source file:com.helpinput.spring.refresher.SessiontRefresher.java

@Override
public void refresh(ApplicationContext context, Map<Class<?>, ScanedType> scanedClasses) {

    boolean needRefreshSessionFactory = false;
    for (Entry<Class<?>, ScanedType> entry : scanedClasses.entrySet()) {
        if (entry.getValue().getValue() > ScanedType.SAME.getValue()
                && entry.getKey().getAnnotation(Entity.class) != null) {
            needRefreshSessionFactory = true;
            break;
        }/* ww  w .  j  a v a  2s  .  co  m*/
    }
    if (needRefreshSessionFactory) {
        DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) ((AbstractApplicationContext) context)
                .getBeanFactory();

        //testUserManager(dlbf);

        final String sessionFactory = "sessionFactory";
        final String annotatedClasses = "annotatedClasses";
        final String setSessionFactory = "setSessionFactory";

        BeanDefinition oldSessionFactoryDef = dlbf.getBeanDefinition(sessionFactory);

        if (oldSessionFactoryDef != null) {
            dlbf.removeBeanDefinition(sessionFactory);
            MutablePropertyValues propertyValues = oldSessionFactoryDef.getPropertyValues();
            PropertyValue oldPropertyValue = propertyValues.getPropertyValue(annotatedClasses);

            propertyValues.removePropertyValue(annotatedClasses);

            BeanDefinition newSessionFactoryDef = BeanDefinitionBuilder
                    .rootBeanDefinition(oldSessionFactoryDef.getBeanClassName()).getBeanDefinition();

            List<PropertyValue> propertyValueList = newSessionFactoryDef.getPropertyValues()
                    .getPropertyValueList();

            propertyValueList.addAll(propertyValues.getPropertyValueList());
            propertyValueList.add(new PropertyValue(annotatedClasses, getManageList(dlbf, oldPropertyValue)));

            dlbf.registerBeanDefinition(sessionFactory, newSessionFactoryDef);

            SessionFactory sessionFactoryImpl = (SessionFactory) dlbf.getBean(sessionFactory);

            String[] beanNames = dlbf.getBeanDefinitionNames();
            for (String beanName : beanNames) {
                BeanDefinition beanDefinition = dlbf.getBeanDefinition(beanName);

                PropertyValues pValues = beanDefinition.getPropertyValues();
                if (pValues.getPropertyValue(sessionFactory) != null) {
                    Object theBean = dlbf.getBean(beanName);
                    Method method = Utils.findMethod(theBean, setSessionFactory, sessionFactoryImpl);
                    if (method != null)
                        Utils.InvokedMethod(theBean, method, sessionFactoryImpl);
                }
            }
        }
    }
}

From source file:nz.co.senanque.validationengine.metadata.AnnotationsMetadataFactory.java

private void scanPackageForValidators(String basePackage,
        Map<Class<? extends Annotation>, Class<? extends FieldValidator<Annotation>>> validators)
        throws ClassNotFoundException {

    ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
            true) {/*from  w  ww  . ja v  a  2s .c o m*/
        private String iface = FieldValidator.class.getCanonicalName();

        /**
         * Check if the class has the right annotation
         * @param metadataReader the ASM ClassReader for the class
         * @return whether the class qualifies as a candidate component
         */
        protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
            AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
            for (String n : metadata.getInterfaceNames()) {
                if (iface.equals(n)) {
                    return true;
                }
            }
            return false;
        }

        /**
         * Determine whether the given bean definition qualifies as candidate.
         * <p>The default implementation checks whether the class is concrete
         * (i.e. not abstract and not an interface). Can be overridden in subclasses.
         * @param beanDefinition the bean definition to check
         * @return whether the bean definition qualifies as a candidate component
         */
        protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
            return (beanDefinition.getMetadata().isConcrete() && beanDefinition.getMetadata().isIndependent());
        }

    };

    //      String basePackage = "nz/co/senanque/validationengine/fieldvalidators";//nz.co.senanque.validationengine.fieldvalidators
    Set<BeanDefinition> components = provider.findCandidateComponents(basePackage.replace('.', '/'));
    for (BeanDefinition component : components) {
        @SuppressWarnings("unchecked")
        Class<? extends FieldValidator<Annotation>> class_ = (Class<? extends FieldValidator<Annotation>>) Class
                .forName(component.getBeanClassName());
        Type[] types = class_.getGenericInterfaces();
        ParameterizedType t0 = (ParameterizedType) types[0];
        @SuppressWarnings("unchecked")
        Class<? extends Annotation> p = (Class<? extends Annotation>) t0.getActualTypeArguments()[0];
        validators.put(p, class_);
    }
}

From source file:org.joinfaces.annotations.JsfCdiToSpringBeanFactoryPostProcessor.java

/**
 * Checks how is bean defined and deduces scope name from JSF CDI annotations.
 *
 * @param definition beanDefinition/*from w ww.jav  a2 s. co  m*/
 */
private void registerJsfCdiToSpring(BeanDefinition definition) {

    if (definition instanceof AnnotatedBeanDefinition) {
        AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;

        String scopeName = null;
        // firstly check whether bean is defined via configuration
        if (annDef.getFactoryMethodMetadata() != null) {
            scopeName = JsfCdiToSpring.deduceScopeName(annDef.getFactoryMethodMetadata());
        } else {
            // fallback to type
            scopeName = JsfCdiToSpring.deduceScopeName(annDef.getMetadata().getAnnotationTypes());
        }

        if (scopeName != null) {
            definition.setScope(scopeName);

            logger.debug(
                    definition.getBeanClassName() + " - Scope(" + definition.getScope().toUpperCase() + ")");
        }
    }
}

From source file:com.mylife.hbase.mapper.HBaseEntityMapper.java

/**
 * Constructor: Sets up hTablePool and scans base package paths looking for classes annotated with @HBasePersistance
 * /* w  w w. ja  v a  2 s.c  o  m*/
 * @param hTablePool
 * @param basePackages
 */
@SuppressWarnings("unchecked")
public HBaseEntityMapper(HTablePool hTablePool, String... basePackages) {

    final HBaseAdmin hBaseAdmin;
    try {
        hBaseAdmin = new HBaseAdmin((Configuration) Whitebox.getInternalState(hTablePool, "config"));
    } catch (IOException e) {
        LOG.fatal("Could not connect to HBase failing HBase object mapping!", e);
        this.hTablePool = null;
        this.annotatedClassToAnnotatedHBaseRowKey = null;
        this.annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethod = null;
        this.annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethod = null;
        this.annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethod = null;
        return;
    }

    this.hTablePool = hTablePool;

    final Map<Class<?>, AccessibleObject> annotatedClassToAnnotatedHBaseRowKeyMap = new HashMap<Class<?>, AccessibleObject>();

    final Map<Class<?>, ImmutableMap<Field, Method>> annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethodMap = new HashMap<Class<?>, ImmutableMap<Field, Method>>();

    final Map<Class<?>, ImmutableMap<Field, Method>> annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethodMap = new HashMap<Class<?>, ImmutableMap<Field, Method>>();

    final Map<Class<?>, ImmutableMap<Field, Method>> annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethodMap = new HashMap<Class<?>, ImmutableMap<Field, Method>>();

    /*
     * Only include classes annotated with @HBasePersistance
     */
    scanner.addIncludeFilter(new AnnotationTypeFilter(HBasePersistance.class));

    for (final String basePackage : basePackages) {

        for (final BeanDefinition beanDefinition : scanner.findCandidateComponents(basePackage)) {
            final Class<?> annotatedClass;
            try {
                annotatedClass = Class.forName(beanDefinition.getBeanClassName());
            } catch (ClassNotFoundException e) {
                // should never happen
                LOG.error("ClassNotFoundException while loading class for HBase entity mapper", e);
                throw new RuntimeException(e);
            }
            /*
             * Get the hbase table name - required!
             */
            final String tableName = annotatedClass.getAnnotation(HBasePersistance.class).tableName();
            if (StringUtils.isEmpty(tableName)) {
                LOG.error("@HBasePersistance must have a non-empty tableName. Ignoring: " + annotatedClass);
                continue;
            }

            try {
                if (!hBaseAdmin.tableExists(tableName)) {
                    LOG.error("table " + tableName
                            + " in @HBasePersistance.tableName() does not exist. Ignoring: " + annotatedClass);
                    continue;
                }
            } catch (IOException e) {
                LOG.error("Could not verify table " + tableName
                        + "in @HBasePersistance.tableName() exists. Ignoring: " + annotatedClass, e);
                continue;
            }

            /*
             * Get the default hbase column family name. This will be used as default column family where fields are
             * mapped to but not required if all annotated fields specifically mention the column family they belong
             * to.
             * 
             * TODO: Current implementation makes this field required but it really isn't based on my
             * comment made previously. That is, if all annotated fields specifically mention the column family
             * where they will be found then a default column family name is unneeded.
             */
            final String defaultColumnFamilyName = annotatedClass.getAnnotation(HBasePersistance.class)
                    .defaultColumnFamilyName();
            if (StringUtils.isEmpty(defaultColumnFamilyName)) {
                LOG.error("@HBasePersistance must have a non-empty defaultColumnFamilyName. Ignoring: "
                        + annotatedClass);
                continue;
            }

            try {
                /*
                 * Confirm the hbase table and column family exists
                 */
                if (!hBaseAdmin.getTableDescriptor(Bytes.toBytes(tableName))
                        .hasFamily(Bytes.toBytes(defaultColumnFamilyName))) {
                    LOG.error("defaultColumnFamilyName (" + defaultColumnFamilyName + ") in " + tableName
                            + "in @HBasePersistance.defaultColumnFamilyName() does not exist. Ignoring: "
                            + annotatedClass);
                    continue;
                }
            } catch (IOException e) {
                LOG.error("Could not verify defaultColumnFamilyName (" + defaultColumnFamilyName + ") in "
                        + tableName + "in @HBasePersistance.defaultColumnFamilyName() exists. Ignoring: "
                        + annotatedClass, e);
                continue;
            }

            /*
             * @HBaseField : Find fields with this annotation and their corresponding getter method
             */
            Set<Field> hBaseFieldAnnotatedFieldsSet = Whitebox
                    .getFieldsAnnotatedWith(Whitebox.newInstance(annotatedClass), HBaseField.class);

            /*
             * Use a Predicate to look through all @HBaseField annotated fields and skip whole class if even one
             * field is not supported
             */
            if (CollectionUtils.exists(hBaseFieldAnnotatedFieldsSet,
                    new org.apache.commons.collections.Predicate() {

                        @Override
                        public boolean evaluate(Object object) {

                            return !TypeHandler.supports(((Field) object).getType());
                        }
                    })) {
                LOG.error("Unsupported type annotated with @HBaseField. Ignoring: " + annotatedClass);
                continue;
            }

            annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethodMap.put(annotatedClass,
                    fieldsToGetterMap(annotatedClass, ImmutableSet.copyOf(hBaseFieldAnnotatedFieldsSet)));

            /*
             * @HBaseObjectField : Find all fields with this annotation and their corresponding getter method
             */
            annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethodMap.put(annotatedClass,
                    fieldsToGetterMap(annotatedClass, ImmutableSet.copyOf(Whitebox.getFieldsAnnotatedWith(
                            Whitebox.newInstance(annotatedClass), HBaseObjectField.class))));

            /*
             * @HBaseMapField : See if this annotation exists and if so, make sure there is only one
             */
            final Set<Field> hBaseMapFieldAnnotatedFieldsSet = Whitebox
                    .getFieldsAnnotatedWith(Whitebox.newInstance(annotatedClass), HBaseMapField.class);

            if (hBaseMapFieldAnnotatedFieldsSet.size() > 1) {
                LOG.error(
                        "@HBaseMapField can only be used on one field per class. Ignoring: " + annotatedClass);
                continue;
            }
            final Iterator<Field> hBaseMapFieldsIterator = hBaseMapFieldAnnotatedFieldsSet.iterator();
            if (hBaseMapFieldsIterator.hasNext()) {
                final Field field = hBaseMapFieldsIterator.next();
                final Type[] types = TypeHandler.getGenericTypesFromField(field);

                if ((Modifier.isAbstract(field.getType().getModifiers()) && !Map.class.equals(field.getType()))
                        || !Map.class.isAssignableFrom(field.getType())
                        || !String.class.equals((Class<?>) types[0])
                        || !String.class.equals((Class<?>) types[1])) {
                    LOG.error(
                            "@HBaseMapField must be used on a field of type java.util.Map<String, String> OR a concrete fields assignable from java.util.Map<String, String> . Ignoring: "
                                    + annotatedClass);
                    continue;
                }
                annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethodMap.put(annotatedClass,
                        fieldsToGetterMap(annotatedClass,
                                ImmutableSet.copyOf(hBaseMapFieldAnnotatedFieldsSet)));

            }

            /*
             * Figure out which method or field to use as the HBaseRowKey this has to be at the end since
             * 
             * @HBaseRowKey is required in the class we can use this to key the other maps we are collecting
             */
            final Set<Field> hBaseRowKeyFields = Whitebox
                    .getFieldsAnnotatedWith(Whitebox.newInstance(annotatedClass), HBaseRowKey.class);
            if (hBaseRowKeyFields.size() > 1) {
                LOG.error("@HBaseRowKey can only be used once per class. Ignoring: " + annotatedClass);
                continue;
            }
            final Collection<Method> hBaseRowKeyMethods = Collections2.filter(
                    Arrays.asList(ReflectionUtils.getAllDeclaredMethods(annotatedClass)),
                    new Predicate<Method>() {

                        @Override
                        public boolean apply(final Method method) {
                            return method.getAnnotation(HBaseRowKey.class) != null;
                        }
                    });
            if (hBaseRowKeyFields.size() + hBaseRowKeyMethods.size() > 1) {
                LOG.error("@HBaseRowKey can only be used once per class. Ignoring: " + annotatedClass);
                continue;
            }

            if (hBaseRowKeyFields.size() + hBaseRowKeyMethods.size() == 0) {
                LOG.error("@HBaseRowKey is required. Ignoring: " + annotatedClass);
                continue;
            }

            if (hBaseRowKeyFields.isEmpty()) {
                final Method hBaseRowKeyMethod = hBaseRowKeyMethods.iterator().next();
                if (hBaseRowKeyMethod.getParameterTypes().length > 0) {
                    LOG.error("@HBaseRowKey can only be used on a no arguemnt method. Ignoring: "
                            + annotatedClass);
                    continue;
                }
                annotatedClassToAnnotatedHBaseRowKeyMap.put(annotatedClass, hBaseRowKeyMethod);
            } else {
                annotatedClassToAnnotatedHBaseRowKeyMap.put(annotatedClass,
                        hBaseRowKeyFields.iterator().next());
            }
        }
    }

    /*
     * keep only the valid classed in our maps
     */
    annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethodMap.keySet()
            .retainAll(annotatedClassToAnnotatedHBaseRowKeyMap.keySet());
    annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethodMap.keySet()
            .retainAll(annotatedClassToAnnotatedHBaseRowKeyMap.keySet());
    annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethodMap.keySet()
            .retainAll(annotatedClassToAnnotatedHBaseRowKeyMap.keySet());

    // set our state
    this.annotatedClassToAnnotatedHBaseRowKey = ImmutableMap.copyOf(annotatedClassToAnnotatedHBaseRowKeyMap);
    this.annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethod = ImmutableMap
            .copyOf(annotatedClassToAnnotatedFieldMappingWithCorrespondingGetterMethodMap);
    this.annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethod = ImmutableMap
            .copyOf(annotatedClassToAnnotatedObjectFieldMappingWithCorrespondingGetterMethodMap);
    this.annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethod = ImmutableMap
            .copyOf(annotatedClassToAnnotatedMapFieldMappingWithCorrespondingGetterMethodMap);
}

From source file:org.alfresco.util.BeanExtender.java

/**
 * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory(org.springframework.beans.factory.config.ConfigurableListableBeanFactory)
 *//*w  w w  .  j  a  v a2s.co m*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    ParameterCheck.mandatory("beanName", beanName);
    ParameterCheck.mandatory("extendingBeanName", extendingBeanName);

    // check for bean name
    if (!beanFactory.containsBean(beanName)) {
        throw new NoSuchBeanDefinitionException("Can't find bean '" + beanName + "' to be extended.");
    }

    // check for extending bean
    if (!beanFactory.containsBean(extendingBeanName)) {
        throw new NoSuchBeanDefinitionException("Can't find bean '" + extendingBeanName
                + "' that is going to extend original bean definition.");
    }

    // get the bean definitions
    BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
    BeanDefinition extendingBeanDefinition = beanFactory.getBeanDefinition(extendingBeanName);

    // update class
    if (StringUtils.isNotBlank(extendingBeanDefinition.getBeanClassName())
            && !beanDefinition.getBeanClassName().equals(extendingBeanDefinition.getBeanClassName())) {
        beanDefinition.setBeanClassName(extendingBeanDefinition.getBeanClassName());
    }

    // update properties
    MutablePropertyValues properties = beanDefinition.getPropertyValues();
    MutablePropertyValues extendingProperties = extendingBeanDefinition.getPropertyValues();
    for (PropertyValue propertyValue : extendingProperties.getPropertyValueList()) {
        properties.add(propertyValue.getName(), propertyValue.getValue());
    }
}

From source file:org.apache.camel.spring.handler.CamelNamespaceHandler.java

private void autoRegisterBeanDefinition(String id, BeanDefinition definition, ParserContext parserContext,
        String contextId) {//from  w ww . j  ava  2s . c  o  m
    // it is a bit cumbersome to work with the spring bean definition parser
    // as we kinda need to eagerly register the bean definition on the parser context
    // and then later we might find out that we should not have done that in case we have multiple camel contexts
    // that would have a id clash by auto registering the same bean definition with the same id such as a producer template

    // see if we have already auto registered this id
    BeanDefinition existing = autoRegisterMap.get(id);
    if (existing == null) {
        // no then add it to the map and register it
        autoRegisterMap.put(id, definition);
        parserContext.registerComponent(new BeanComponentDefinition(definition, id));
        if (LOG.isDebugEnabled()) {
            LOG.debug("Registered default: " + definition.getBeanClassName() + " with id: " + id
                    + " on camel context: " + contextId);
        }
    } else {
        // ups we have already registered it before with same id, but on another camel context
        // this is not good so we need to remove all traces of this auto registering.
        // end user must manually add the needed XML elements and provide unique ids access all camel context himself.
        if (LOG.isDebugEnabled()) {
            LOG.debug("Unregistered default: " + definition.getBeanClassName() + " with id: " + id
                    + " as we have multiple camel contexts and they must use unique ids."
                    + " You must define the definition in the XML file manually to avoid id clashes when using multiple camel contexts");
        }

        parserContext.getRegistry().removeBeanDefinition(id);
    }
}