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); } }
/** * 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); }
@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(); } } }
@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; }
/** * 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; }
/** * 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); } }
/** * 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; }
/** * 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; }
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(); } } }
@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; }
/** * 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; }
/** * 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; }
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(); }
/** * 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); } }
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); } }
/** * 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); }
/** * 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); } }
/** * {@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(); }
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; }
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; }
/** * Register the given BeanPostProcessor beans. */ private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) { for (BeanPostProcessor postProcessor : postProcessors) { beanFactory.addBeanPostProcessor(postProcessor); } }
/** * Register the given BeanPostProcessor beans. */ private static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) { for (BeanPostProcessor postProcessor : postProcessors) { beanFactory.addBeanPostProcessor(postProcessor); } }
@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; }
/** * 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); }