Java 类org.springframework.beans.factory.config.BeanPostProcessor 实例源码

项目:gemini.blueprint    文件:OsgiAnnotationPostProcessor.java   
public void postProcessBeanFactory(BundleContext bundleContext, ConfigurableListableBeanFactory beanFactory)
        throws BeansException, OsgiException {

    Bundle bundle = bundleContext.getBundle();
    try {
        // Try and load the annotation code using the bundle classloader
        Class<?> annotationBppClass = bundle.loadClass(ANNOTATION_BPP_CLASS);
        // instantiate the class
        final BeanPostProcessor annotationBeanPostProcessor = (BeanPostProcessor) BeanUtils.instantiateClass(annotationBppClass);

        // everything went okay so configure the BPP and add it to the BF
        ((BeanFactoryAware) annotationBeanPostProcessor).setBeanFactory(beanFactory);
        ((BeanClassLoaderAware) annotationBeanPostProcessor).setBeanClassLoader(beanFactory.getBeanClassLoader());
        ((BundleContextAware) annotationBeanPostProcessor).setBundleContext(bundleContext);
        beanFactory.addBeanPostProcessor(annotationBeanPostProcessor);
    }
    catch (ClassNotFoundException exception) {
        log.info("Spring-DM annotation package could not be loaded from bundle ["
                + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "]; annotation processing disabled...");
        if (log.isDebugEnabled())
            log.debug("Cannot load annotation injection processor", exception);
    }
}
项目:gemini.blueprint    文件:AbstractOsgiBundleApplicationContext.java   
/**
 * Takes care of enforcing the relationship between exporter and importers.
 * 
 * @param beanFactory
 */
private void enforceExporterImporterDependency(ConfigurableListableBeanFactory beanFactory) {
    Object instance = null;

    instance = AccessController.doPrivileged(new PrivilegedAction<Object>() {

        public Object run() {
            // create the service manager
            ClassLoader loader = AbstractOsgiBundleApplicationContext.class.getClassLoader();
            try {
                Class<?> managerClass = loader.loadClass(EXPORTER_IMPORTER_DEPENDENCY_MANAGER);
                return BeanUtils.instantiateClass(managerClass);
            } catch (ClassNotFoundException cnfe) {
                throw new ApplicationContextException("Cannot load class " + EXPORTER_IMPORTER_DEPENDENCY_MANAGER,
                        cnfe);
            }
        }
    });

    // sanity check
    Assert.isInstanceOf(BeanFactoryAware.class, instance);
    Assert.isInstanceOf(BeanPostProcessor.class, instance);
    ((BeanFactoryAware) instance).setBeanFactory(beanFactory);
    beanFactory.addBeanPostProcessor((BeanPostProcessor) instance);
}
项目:lams    文件:ScriptFactoryPostProcessor.java   
@Override
public void setBeanFactory(BeanFactory beanFactory) {
    if (!(beanFactory instanceof ConfigurableBeanFactory)) {
        throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with a BeanFactory "
                + "which does not implement ConfigurableBeanFactory: " + beanFactory.getClass());
    }
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;

    // Required so that references (up container hierarchies) are correctly resolved.
    this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }
}
项目:lams    文件:AbstractAutowireCapableBeanFactory.java   
@Override
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
    Class<?> targetType = mbd.getTargetType();
    if (targetType == null) {
        targetType = (mbd.getFactoryMethodName() != null ? getTypeForFactoryMethod(beanName, mbd, typesToMatch) :
                resolveBeanClass(mbd, beanName, typesToMatch));
        if (ObjectUtils.isEmpty(typesToMatch) || getTempClassLoader() == null) {
            mbd.setTargetType(targetType);
        }
    }
    // Apply SmartInstantiationAwareBeanPostProcessors to predict the
    // eventual type after a before-instantiation shortcut.
    if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Class<?> predicted = ibp.predictBeanType(targetType, beanName);
                if (predicted != null && (typesToMatch.length != 1 || !FactoryBean.class.equals(typesToMatch[0]) ||
                        FactoryBean.class.isAssignableFrom(predicted))) {
                    return predicted;
                }
            }
        }
    }
    return targetType;
}
项目:lams    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Obtain a reference for early access to the specified bean,
 * typically for the purpose of resolving a circular reference.
 * @param beanName the name of the bean (for error handling purposes)
 * @param mbd the merged bean definition for the bean
 * @param bean the raw bean instance
 * @return the object to expose as bean reference
 */
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    Object exposedObject = bean;
    if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
                if (exposedObject == null) {
                    return exposedObject;
                }
            }
        }
    }
    return exposedObject;
}
项目:lams    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Apply MergedBeanDefinitionPostProcessors to the specified bean definition,
 * invoking their {@code postProcessMergedBeanDefinition} methods.
 * @param mbd the merged bean definition for the bean
 * @param beanType the actual type of the managed bean instance
 * @param beanName the name of the bean
 * @throws BeansException if any post-processing failed
 * @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
 */
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)
        throws BeansException {

    try {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof MergedBeanDefinitionPostProcessor) {
                MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
            }
        }
    }
    catch (Exception ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Post-processing failed of bean type [" + beanType + "] failed", ex);
    }
}
项目:lams    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Determine candidate constructors to use for the given bean, checking all registered
 * {@link SmartInstantiationAwareBeanPostProcessor SmartInstantiationAwareBeanPostProcessors}.
 * @param beanClass the raw class of the bean
 * @param beanName the name of the bean
 * @return the candidate constructors, or {@code null} if none specified
 * @throws org.springframework.beans.BeansException in case of errors
 * @see org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
 */
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(Class<?> beanClass, String beanName)
        throws BeansException {

    if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                if (ctors != null) {
                    return ctors;
                }
            }
        }
    }
    return null;
}
项目:lams    文件:AbstractBeanFactoryBasedTargetSourceCreator.java   
/**
 * Build an internal BeanFactory for resolving target beans.
 * @param containingFactory the containing BeanFactory that originally defines the beans
 * @return an independent internal BeanFactory to hold copies of some target beans
 */
protected DefaultListableBeanFactory buildInternalBeanFactory(ConfigurableBeanFactory containingFactory) {
    // Set parent so that references (up container hierarchies) are correctly resolved.
    DefaultListableBeanFactory internalBeanFactory = new DefaultListableBeanFactory(containingFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    internalBeanFactory.copyConfigurationFrom(containingFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = internalBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }

    return internalBeanFactory;
}
项目:game    文件:MyScriptFactoryPostProcessor.java   
public void setBeanFactory(BeanFactory beanFactory) {
if (!(beanFactory instanceof ConfigurableBeanFactory)) {
    throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with a BeanFactory "
        + "which does not implement ConfigurableBeanFactory: " + beanFactory.getClass());
}
this.beanFactory = (ConfigurableBeanFactory) beanFactory;

// Required so that references (up container hierarchies) are correctly
// resolved.
this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);

// Required so that all BeanPostProcessors, Scopes, etc become
// available.
this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);

// Filter out BeanPostProcessors that are part of the AOP
// infrastructure,
// since those are only meant to apply to beans defined in the original
// factory.
for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it
    .hasNext();) {
    if (it.next() instanceof AopInfrastructureBean) {
    it.remove();
    }
}
   }
项目:spring4-understanding    文件:ScriptFactoryPostProcessor.java   
@Override
public void setBeanFactory(BeanFactory beanFactory) {
    if (!(beanFactory instanceof ConfigurableBeanFactory)) {
        throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with a BeanFactory "
                + "which does not implement ConfigurableBeanFactory: " + beanFactory.getClass());
    }
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;

    // Required so that references (up container hierarchies) are correctly resolved.
    this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }
}
项目:spring4-understanding    文件:AbstractAutowireCapableBeanFactory.java   
@Override
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
    Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);

    // Apply SmartInstantiationAwareBeanPostProcessors to predict the
    // eventual type after a before-instantiation shortcut.
    if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Class<?> predicted = ibp.predictBeanType(targetType, beanName);
                if (predicted != null && (typesToMatch.length != 1 || FactoryBean.class != typesToMatch[0] ||
                        FactoryBean.class.isAssignableFrom(predicted))) {
                    return predicted;
                }
            }
        }
    }
    return targetType;
}
项目:spring4-understanding    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Obtain a reference for early access to the specified bean,
 * typically for the purpose of resolving a circular reference.
 * @param beanName the name of the bean (for error handling purposes)
 * @param mbd the merged bean definition for the bean
 * @param bean the raw bean instance
 * @return the object to expose as bean reference
 */
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    Object exposedObject = bean;
    if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
                if (exposedObject == null) {
                    return exposedObject;
                }
            }
        }
    }
    return exposedObject;
}
项目:spring4-understanding    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Apply MergedBeanDefinitionPostProcessors to the specified bean definition,
 * invoking their {@code postProcessMergedBeanDefinition} methods.
 * @param mbd the merged bean definition for the bean
 * @param beanType the actual type of the managed bean instance
 * @param beanName the name of the bean
 * @throws BeansException if any post-processing failed
 * @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
 */
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)
        throws BeansException {

    try {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof MergedBeanDefinitionPostProcessor) {
                MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
            }
        }
    }
    catch (Exception ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Post-processing failed of bean type [" + beanType + "] failed", ex);
    }
}
项目:spring4-understanding    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Determine candidate constructors to use for the given bean, checking all registered
 * {@link SmartInstantiationAwareBeanPostProcessor SmartInstantiationAwareBeanPostProcessors}.
 * @param beanClass the raw class of the bean
 * @param beanName the name of the bean
 * @return the candidate constructors, or {@code null} if none specified
 * @throws org.springframework.beans.BeansException in case of errors
 * @see org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
 */
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(Class<?> beanClass, String beanName)
        throws BeansException {

    if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                if (ctors != null) {
                    return ctors;
                }
            }
        }
    }
    return null;
}
项目:my-spring-cache-redis    文件:ScriptFactoryPostProcessor.java   
@Override
public void setBeanFactory(BeanFactory beanFactory) {
    if (!(beanFactory instanceof ConfigurableBeanFactory)) {
        throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with a BeanFactory "
                + "which does not implement ConfigurableBeanFactory: " + beanFactory.getClass());
    }
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;

    // Required so that references (up container hierarchies) are correctly resolved.
    this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }
}
项目:spring    文件:ScriptFactoryPostProcessor.java   
@Override
public void setBeanFactory(BeanFactory beanFactory) {
    if (!(beanFactory instanceof ConfigurableBeanFactory)) {
        throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with a BeanFactory "
                + "which does not implement ConfigurableBeanFactory: " + beanFactory.getClass());
    }
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;

    // Required so that references (up container hierarchies) are correctly resolved.
    this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }
}
项目:spring    文件:DisposableBeanAdapter.java   
/**
 * Search for all DestructionAwareBeanPostProcessors in the List.
 * @param processors the List to search
 * @return the filtered List of DestructionAwareBeanPostProcessors
 */
private List<DestructionAwareBeanPostProcessor> filterPostProcessors(List<BeanPostProcessor> processors, Object bean) {
    List<DestructionAwareBeanPostProcessor> filteredPostProcessors = null;
    if (!CollectionUtils.isEmpty(processors)) {
        filteredPostProcessors = new ArrayList<DestructionAwareBeanPostProcessor>(processors.size());
        for (BeanPostProcessor processor : processors) {
            if (processor instanceof DestructionAwareBeanPostProcessor) {
                DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
                try {
                    if (dabpp.requiresDestruction(bean)) {
                        filteredPostProcessors.add(dabpp);
                    }
                }
                catch (AbstractMethodError err) {
                    // A pre-4.3 third-party DestructionAwareBeanPostProcessor...
                    // As of 5.0, we can let requiresDestruction be a Java 8 default method which returns true.
                    filteredPostProcessors.add(dabpp);
                }
            }
        }
    }
    return filteredPostProcessors;
}
项目:spring    文件:DisposableBeanAdapter.java   
/**
 * Check whether the given bean has destruction-aware post-processors applying to it.
 * @param bean the bean instance
 * @param postProcessors the post-processor candidates
 */
public static boolean hasApplicableProcessors(Object bean, List<BeanPostProcessor> postProcessors) {
    if (!CollectionUtils.isEmpty(postProcessors)) {
        for (BeanPostProcessor processor : postProcessors) {
            if (processor instanceof DestructionAwareBeanPostProcessor) {
                DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
                try {
                    if (dabpp.requiresDestruction(bean)) {
                        return true;
                    }
                }
                catch (AbstractMethodError err) {
                    // A pre-4.3 third-party DestructionAwareBeanPostProcessor...
                    // As of 5.0, we can let requiresDestruction be a Java 8 default method which returns true.
                    return true;
                }
            }
        }
    }
    return false;
}
项目:spring    文件:AbstractAutowireCapableBeanFactory.java   
@Override
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
    Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);

    // Apply SmartInstantiationAwareBeanPostProcessors to predict the
    // eventual type after a before-instantiation shortcut.
    if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Class<?> predicted = ibp.predictBeanType(targetType, beanName);
                if (predicted != null && (typesToMatch.length != 1 || FactoryBean.class != typesToMatch[0] ||
                        FactoryBean.class.isAssignableFrom(predicted))) {
                    return predicted;
                }
            }
        }
    }
    return targetType;
}
项目:spring    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Obtain a reference for early access to the specified bean,
 * typically for the purpose of resolving a circular reference.
 * @param beanName the name of the bean (for error handling purposes)
 * @param mbd the merged bean definition for the bean
 * @param bean the raw bean instance
 * @return the object to expose as bean reference
 */
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    Object exposedObject = bean;
    if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
                if (exposedObject == null) {
                    return exposedObject;
                }
            }
        }
    }
    return exposedObject;
}
项目:spring    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Apply MergedBeanDefinitionPostProcessors to the specified bean definition,
 * invoking their {@code postProcessMergedBeanDefinition} methods.
 * @param mbd the merged bean definition for the bean
 * @param beanType the actual type of the managed bean instance
 * @param beanName the name of the bean
 * @throws BeansException if any post-processing failed
 * @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
 */
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)
        throws BeansException {

    try {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof MergedBeanDefinitionPostProcessor) {
                MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
            }
        }
    }
    catch (Exception ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Post-processing failed of bean type [" + beanType + "] failed", ex);
    }
}
项目:spring    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Determine candidate constructors to use for the given bean, checking all registered
 * {@link SmartInstantiationAwareBeanPostProcessor SmartInstantiationAwareBeanPostProcessors}.
 * @param beanClass the raw class of the bean
 * @param beanName the name of the bean
 * @return the candidate constructors, or {@code null} if none specified
 * @throws org.springframework.beans.BeansException in case of errors
 * @see org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
 */
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(Class<?> beanClass, String beanName)
        throws BeansException {

    if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                if (ctors != null) {
                    return ctors;
                }
            }
        }
    }
    return null;
}
项目:spring    文件:AbstractBeanFactoryBasedTargetSourceCreator.java   
/**
 * Build an internal BeanFactory for resolving target beans.
 * @param containingFactory the containing BeanFactory that originally defines the beans
 * @return an independent internal BeanFactory to hold copies of some target beans
 */
protected DefaultListableBeanFactory buildInternalBeanFactory(ConfigurableBeanFactory containingFactory) {
    // Set parent so that references (up container hierarchies) are correctly resolved.
    DefaultListableBeanFactory internalBeanFactory = new DefaultListableBeanFactory(containingFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    internalBeanFactory.copyConfigurationFrom(containingFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = internalBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }

    return internalBeanFactory;
}
项目:CodesOfLightweightJavaEE    文件:BeanTest.java   
public static void main(String[] args)throws Exception
    {
        // �������·���µ�beans.xml�ļ�������Spring����
//      ApplicationContext ctx = new
//          ClassPathXmlApplicationContext("beans.xml");
//      Person p = (Person)ctx.getBean("chinese");

        // ���������·���µ�beans.xml�ļ�����Resource����
        Resource isr = new ClassPathResource("beans.xml");
        // ����Ĭ�ϵ�BeanFactory����
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        // ��Ĭ�ϵ�BeanFactory��������isr��Ӧ��XML�����ļ�
        new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions(isr);
        // ��ȡ�����е�Bean������
        BeanPostProcessor bp = (BeanPostProcessor)beanFactory.getBean("bp");
        // ע��Bean������
        beanFactory.addBeanPostProcessor(bp);
        Person p = (Person)beanFactory.getBean("chinese");

        p.useAxe();
    }
项目:class-guard    文件:ScriptFactoryPostProcessor.java   
@Override
public void setBeanFactory(BeanFactory beanFactory) {
    if (!(beanFactory instanceof ConfigurableBeanFactory)) {
        throw new IllegalStateException("ScriptFactoryPostProcessor doesn't work with a BeanFactory "
                + "which does not implement ConfigurableBeanFactory: " + beanFactory.getClass());
    }
    this.beanFactory = (ConfigurableBeanFactory) beanFactory;

    // Required so that references (up container hierarchies) are correctly resolved.
    this.scriptBeanFactory.setParentBeanFactory(this.beanFactory);

    // Required so that all BeanPostProcessors, Scopes, etc become available.
    this.scriptBeanFactory.copyConfigurationFrom(this.beanFactory);

    // Filter out BeanPostProcessors that are part of the AOP infrastructure,
    // since those are only meant to apply to beans defined in the original factory.
    for (Iterator<BeanPostProcessor> it = this.scriptBeanFactory.getBeanPostProcessors().iterator(); it.hasNext();) {
        if (it.next() instanceof AopInfrastructureBean) {
            it.remove();
        }
    }
}
项目:class-guard    文件:AbstractAutowireCapableBeanFactory.java   
@Override
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
    Class<?> targetType = mbd.getTargetType();
    if (targetType == null) {
        targetType = (mbd.getFactoryMethodName() != null ? getTypeForFactoryMethod(beanName, mbd, typesToMatch) :
                resolveBeanClass(mbd, beanName, typesToMatch));
        if (ObjectUtils.isEmpty(typesToMatch) || getTempClassLoader() == null) {
            mbd.setTargetType(targetType);
        }
    }
    // Apply SmartInstantiationAwareBeanPostProcessors to predict the
    // eventual type after a before-instantiation shortcut.
    if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Class<?> predicted = ibp.predictBeanType(targetType, beanName);
                if (predicted != null && (typesToMatch.length != 1 || !FactoryBean.class.equals(typesToMatch[0]) ||
                        FactoryBean.class.isAssignableFrom(predicted))) {
                    return predicted;
                }
            }
        }
    }
    return targetType;
}
项目:class-guard    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Obtain a reference for early access to the specified bean,
 * typically for the purpose of resolving a circular reference.
 * @param beanName the name of the bean (for error handling purposes)
 * @param mbd the merged bean definition for the bean
 * @param bean the raw bean instance
 * @return the object to expose as bean reference
 */
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
    Object exposedObject = bean;
    if (bean != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
                if (exposedObject == null) {
                    return exposedObject;
                }
            }
        }
    }
    return exposedObject;
}
项目:class-guard    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Apply MergedBeanDefinitionPostProcessors to the specified bean definition,
 * invoking their {@code postProcessMergedBeanDefinition} methods.
 * @param mbd the merged bean definition for the bean
 * @param beanType the actual type of the managed bean instance
 * @param beanName the name of the bean
 * @throws BeansException if any post-processing failed
 * @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
 */
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)
        throws BeansException {

    try {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof MergedBeanDefinitionPostProcessor) {
                MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
            }
        }
    }
    catch (Exception ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Post-processing failed of bean type [" + beanType + "] failed", ex);
    }
}
项目:class-guard    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Determine candidate constructors to use for the given bean, checking all registered
 * {@link SmartInstantiationAwareBeanPostProcessor SmartInstantiationAwareBeanPostProcessors}.
 * @param beanClass the raw class of the bean
 * @param beanName the name of the bean
 * @return the candidate constructors, or {@code null} if none specified
 * @throws org.springframework.beans.BeansException in case of errors
 * @see org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
 */
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(Class<?> beanClass, String beanName)
        throws BeansException {

    if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                if (ctors != null) {
                    return ctors;
                }
            }
        }
    }
    return null;
}
项目:rice    文件:DataDictionary.java   
/**
 * Sets up the bean post processor and conversion service
 *
 * @param beans - The bean factory for the the dictionary beans
 */
public static void setupProcessor(DefaultListableBeanFactory beans) {
    try {
        // UIF post processor that sets component ids
        BeanPostProcessor idPostProcessor = ComponentBeanPostProcessor.class.newInstance();
        beans.addBeanPostProcessor(idPostProcessor);
        beans.setBeanExpressionResolver(new StandardBeanExpressionResolver() {
            @Override
            protected void customizeEvaluationContext(StandardEvaluationContext evalContext) {
                try {
                    evalContext.registerFunction("getService", ExpressionFunctions.class.getDeclaredMethod("getService", new Class[]{String.class}));
                } catch(NoSuchMethodException me) {
                    LOG.error("Unable to register custom expression to data dictionary bean factory", me);
                }
            }
        });

        // special converters for shorthand map and list property syntax
        GenericConversionService conversionService = new GenericConversionService();
        conversionService.addConverter(new StringMapConverter());
        conversionService.addConverter(new StringListConverter());

        beans.setConversionService(conversionService);
    } catch (Exception e1) {
        throw new DataDictionaryException("Cannot create component decorator post processor: " + e1.getMessage(),
                e1);
    }
}
项目:spring-osgi    文件:OsgiAnnotationPostProcessor.java   
public void postProcessBeanFactory(BundleContext bundleContext, ConfigurableListableBeanFactory beanFactory)
        throws BeansException, OsgiException {

    Bundle bundle = bundleContext.getBundle();
    try {
        // Try and load the annotation code using the bundle classloader
        Class annotationBppClass = bundle.loadClass(ANNOTATION_BPP_CLASS);
        // instantiate the class
        final BeanPostProcessor annotationBeanPostProcessor = (BeanPostProcessor) BeanUtils.instantiateClass(annotationBppClass);

        // everything went okay so configure the BPP and add it to the BF
        ((BeanFactoryAware) annotationBeanPostProcessor).setBeanFactory(beanFactory);
        ((BeanClassLoaderAware) annotationBeanPostProcessor).setBeanClassLoader(beanFactory.getBeanClassLoader());
        ((BundleContextAware) annotationBeanPostProcessor).setBundleContext(bundleContext);
        beanFactory.addBeanPostProcessor(annotationBeanPostProcessor);
    }
    catch (ClassNotFoundException exception) {
        log.info("Spring-DM annotation package could not be loaded from bundle ["
                + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "]; annotation processing disabled...");
        if (log.isDebugEnabled())
            log.debug("Cannot load annotation injection processor", exception);
    }
}
项目:spring-osgi    文件:AbstractOsgiBundleApplicationContext.java   
/**
 * Takes care of enforcing the relationship between exporter and importers.
 * 
 * @param beanFactory
 */
private void enforceExporterImporterDependency(ConfigurableListableBeanFactory beanFactory) {
    Object instance = null;

    instance = AccessController.doPrivileged(new PrivilegedAction() {

        public Object run() {
            // create the service manager
            ClassLoader loader = AbstractOsgiBundleApplicationContext.class.getClassLoader();
            try {
                Class managerClass = loader.loadClass(EXPORTER_IMPORTER_DEPENDENCY_MANAGER);
                return BeanUtils.instantiateClass(managerClass);
            }
            catch (ClassNotFoundException cnfe) {
                throw new ApplicationContextException("Cannot load class " + EXPORTER_IMPORTER_DEPENDENCY_MANAGER,
                    cnfe);
            }
        }
    });

    // sanity check
    Assert.isInstanceOf(BeanFactoryAware.class, instance);
    Assert.isInstanceOf(BeanPostProcessor.class, instance);
    ((BeanFactoryAware) instance).setBeanFactory(beanFactory);
    beanFactory.addBeanPostProcessor((BeanPostProcessor) instance);
}
项目:kuali_rice    文件:DataDictionary.java   
/**
 * Sets up the bean post processor and conversion service
 *
 * @param beans - The bean factory for the the dictionary beans
 */
public static void setupProcessor(KualiDefaultListableBeanFactory beans) {
    try {
        // UIF post processor that sets component ids
        BeanPostProcessor idPostProcessor = ComponentBeanPostProcessor.class.newInstance();
        beans.addBeanPostProcessor(idPostProcessor);
        beans.setBeanExpressionResolver(new StandardBeanExpressionResolver());

        // special converters for shorthand map and list property syntax
        GenericConversionService conversionService = new GenericConversionService();
        conversionService.addConverter(new StringMapConverter());
        conversionService.addConverter(new StringListConverter());

        beans.setConversionService(conversionService);
    } catch (Exception e1) {
        throw new DataDictionaryException("Cannot create component decorator post processor: " + e1.getMessage(),
                e1);
    }
}
项目:cas-5.1.0    文件:CasWebApplicationContext.java   
/**
 * {@inheritDoc}
 * Reset the value resolver on the inner {@link ScheduledAnnotationBeanPostProcessor}
 * so that we can parse durations. This is due to how {@link org.springframework.scheduling.annotation.SchedulingConfiguration}
 * creates the processor and does not provide a way for one to inject a value resolver.
 */
@Override
protected void onRefresh() {
    final ScheduledAnnotationBeanPostProcessor sch = (ScheduledAnnotationBeanPostProcessor)
            getBeanFactory().getBean(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME, BeanPostProcessor.class);
    sch.setEmbeddedValueResolver(new CasConfigurationEmbeddedValueResolver(this));
    super.onRefresh();
}
项目:gemini.blueprint    文件:ServiceReferenceInjectionBeanPostProcessor.java   
public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
        String beanName) throws BeansException {

    MutablePropertyValues newprops = new MutablePropertyValues(pvs);
    for (PropertyDescriptor pd : pds) {
        ServiceReference s = hasServiceProperty(pd);
        if (s != null && !pvs.contains(pd.getName())) {
            try {
                if (logger.isDebugEnabled())
                    logger.debug("Processing annotation [" + s + "] for [" + beanName + "." + pd.getName() + "]");
                FactoryBean importer = getServiceImporter(s, pd.getWriteMethod(), beanName);
                // BPPs are created in stageOne(), even though they are run in stageTwo(). This check means that
                // the call to getObject() will not fail with ServiceUnavailable. This is safe to do because
                // ServiceReferenceDependencyBeanFactoryPostProcessor will ensure that mandatory services are
                // satisfied before stageTwo() is run.
                if (bean instanceof BeanPostProcessor) {
                    ImporterCallAdapter.setCardinality(importer, Availability.OPTIONAL);
                }
                newprops.addPropertyValue(pd.getName(), importer.getObject());
            }
            catch (Exception e) {
                throw new FatalBeanException("Could not create service reference", e);
            }
        }
    }
    return newprops;
}
项目:gemini.blueprint    文件:AbstractDelegatedExecutionApplicationContext.java   
public Object postProcessAfterInitialization(Object bean, String beanName) {
    if (!(bean instanceof BeanPostProcessor)
            && this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
        if (logger.isInfoEnabled()) {
            logger.info("Bean '" + beanName + "' is not eligible for getting processed by all "
                    + "BeanPostProcessors (for example: not eligible for auto-proxying)");
        }
    }
    return bean;
}
项目:gemini.blueprint    文件:AbstractDelegatedExecutionApplicationContext.java   
/**
 * Register the given BeanPostProcessor beans.
 */
private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory,
        List<BeanPostProcessor> postProcessors) {

    for (BeanPostProcessor postProcessor : postProcessors) {
        beanFactory.addBeanPostProcessor(postProcessor);
    }
}
项目:lams    文件:PostProcessorRegistrationDelegate.java   
/**
 * Register the given BeanPostProcessor beans.
 */
private static void registerBeanPostProcessors(
        ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

    for (BeanPostProcessor postProcessor : postProcessors) {
        beanFactory.addBeanPostProcessor(postProcessor);
    }
}
项目:lams    文件:PostProcessorRegistrationDelegate.java   
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
    if (bean != null && !(bean instanceof BeanPostProcessor) &&
            this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
        if (logger.isInfoEnabled()) {
            logger.info("Bean '" + beanName + "' of type [" + bean.getClass() +
                    "] is not eligible for getting processed by all BeanPostProcessors " +
                    "(for example: not eligible for auto-proxying)");
        }
    }
    return bean;
}
项目:lams    文件:DisposableBeanAdapter.java   
/**
 * Create a new DisposableBeanAdapter for the given bean.
 * @param bean the bean instance (never {@code null})
 * @param beanName the name of the bean
 * @param beanDefinition the merged bean definition
 * @param postProcessors the List of BeanPostProcessors
 * (potentially DestructionAwareBeanPostProcessor), if any
 */
public DisposableBeanAdapter(Object bean, String beanName, RootBeanDefinition beanDefinition,
        List<BeanPostProcessor> postProcessors, AccessControlContext acc) {

    Assert.notNull(bean, "Disposable bean must not be null");
    this.bean = bean;
    this.beanName = beanName;
    this.invokeDisposableBean =
            (this.bean instanceof DisposableBean && !beanDefinition.isExternallyManagedDestroyMethod("destroy"));
    this.nonPublicAccessAllowed = beanDefinition.isNonPublicAccessAllowed();
    this.acc = acc;
    String destroyMethodName = inferDestroyMethodIfNecessary(bean, beanDefinition);
    if (destroyMethodName != null && !(this.invokeDisposableBean && "destroy".equals(destroyMethodName)) &&
            !beanDefinition.isExternallyManagedDestroyMethod(destroyMethodName)) {
        this.destroyMethodName = destroyMethodName;
        this.destroyMethod = determineDestroyMethod();
        if (this.destroyMethod == null) {
            if (beanDefinition.isEnforceDestroyMethod()) {
                throw new BeanDefinitionValidationException("Couldn't find a destroy method named '" +
                        destroyMethodName + "' on bean with name '" + beanName + "'");
            }
        }
        else {
            Class<?>[] paramTypes = this.destroyMethod.getParameterTypes();
            if (paramTypes.length > 1) {
                throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" +
                        beanName + "' has more than one parameter - not supported as destroy method");
            }
            else if (paramTypes.length == 1 && !paramTypes[0].equals(boolean.class)) {
                throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" +
                        beanName + "' has a non-boolean parameter - not supported as destroy method");
            }
        }
    }
    this.beanPostProcessors = filterPostProcessors(postProcessors);
}