有没有办法使用自定义BeanWrapper实现加载应用程序上下文

Dav*_*ith 7 java spring scala javabeans

我希望能够将使用setter注入的Spring用于Scala组件.不幸的是,Scala的本地setter的命名与JavaBeans标准不同,foo_=而不是setFoo.Scala确实为此提供了几种解决方法,注释强制创建JavaBeans setter/getter以及本机Scala,但这需要注释我想要注入的每个组件.更方便的是BeanWrapper用一个知道如何处理Scala风格的getter和setter的方法覆盖Spring使用的方法.

似乎没有任何关于如何做这样的事情的文件,或者它是否可行,也没有其他任何人做过的在线例子.所以在深入研究之前,我想我会在这里查看

Geo*_*uba 3

看起来AbstractAutowireCapableBeanFactory(BeanWrapper 的大部分工作都已完成)已被硬编码为使用BeanWrapperImpl. 那里没有延伸的意义。依次BeanWrapperImpl使用CachedIntrospectionResults哪个使用。Introspector看起来没有办法配置任何这些依赖项。我们可以尝试使用标准扩展点:BeanPostProcessorBeanFactoryPostProcessor

使用 justBeanPostProcessor是行不通的,因为如果我们做这样的事情:

<bean id="beanForInjection" class="com.test.BeanForInjection">
    <property name="bean" ref="beanToBeInjected"/>        
</bean>
Run Code Online (Sandbox Code Playgroud)

BeanForInjectionScala 类在哪里

package com.test
import com.other.BeanToBeInjected

class BeanForInjection {
    var bean : BeanToBeInjected = null;
}
Run Code Online (Sandbox Code Playgroud)

并且BeanToBeInjected是我们想要注入的bean,那么我们将在BeanPostProcessor有机会介入之前捕获异常。在调用任何回调之前,Beans 会填充值BeanPostProcessor

但是我们可以用来BeanFactoryPostProcessor“隐藏”预期通过类似 Scala 的 setter 注入的属性,并在稍后应用它们。

像这样的东西:

package com.other;

import ...

public class ScalaAwareBeanFactoryPostProcessor implements BeanFactoryPostProcessor, PriorityOrdered {

    ... PriorityOrdered related methods...

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        String[] beanNames = beanFactory.getBeanDefinitionNames();
        for (String currentName : beanNames) {
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(currentName);
            processScalaProperties(beanDefinition);
        }
    }

    protected void processScalaProperties(BeanDefinition beanDefinition) {
        String className = beanDefinition.getBeanClassName();
        try {
            Set<PropertyValue> scalaProperties = new HashSet<PropertyValue>();
            for (PropertyValue propertyValue : beanDefinition.getPropertyValues().getPropertyValueList()) {
                String scalaSetterName = ScalaAwarePostProcessorUtils.getScalaSetterName(propertyValue.getName());

                BeanInfo beanInfo = getBeanInfo(className);
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors();
                for (MethodDescriptor md : methodDescriptors) {

                    if (scalaSetterName.equals(md.getName())) {
                        boolean isScalaProperty = true;
                        for (PropertyDescriptor pd : propertyDescriptors) {
                            if (propertyValue.getName().equals(pd.getName())) {
                                isScalaProperty = false;
                            }
                        }
                        if (isScalaProperty) {
                            scalaProperties.add(propertyValue);
                        }
                    }
                }
            }

            if (!scalaProperties.isEmpty()) {
                beanDefinition.setAttribute(ScalaAwarePostProcessorUtils.SCALA_ATTRIBUTES_KEY, scalaProperties);
            }

            for (PropertyValue propertyValue : scalaProperties) {
                beanDefinition.getPropertyValues().removePropertyValue(propertyValue);
            }
        } catch (ClassNotFoundException e) {
        } catch (IntrospectionException e) {
        }
    }

    private BeanInfo getBeanInfo(String className) throws ClassNotFoundException, IntrospectionException {
        Class beanClass = Class.forName(className);
        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
        cleanIntrospectorCache(beanClass);
        return beanInfo;
    }

    private void cleanIntrospectorCache(Class beanClass) {
        Class classToFlush = beanClass;
        do {
            Introspector.flushFromCaches(classToFlush);
            classToFlush = classToFlush.getSuperclass();
        }
        while (classToFlush != null);
    }
}
Run Code Online (Sandbox Code Playgroud)

此实现只是检查是否有任何 bean 具有未列为属性的属性,并且还具有类似 Scala 的 setter。与此约定匹配的所有属性都将从属性列表中删除并保存为 bean 的属性。现在,我们所需要做的就是为每个 bean 提取这些属性(如果有)并应用它们。这就是我们需要的地方BeanPostProcessor(AutowiredAnnotationBeanPostProcessor 就是 BeanPostProcessor 的一个很好的例子)。

package com.other;

public class ScalaAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
    implements PriorityOrdered, BeanFactoryAware {

    private ConfigurableListableBeanFactory beanFactory;

    ... Order related stuff...

    public void setBeanFactory(BeanFactory beanFactory) {
        if (beanFactory instanceof ConfigurableListableBeanFactory) {
            this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
        }
    }

    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs,     PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
        try {
            InjectionMetadata metadata = findScalaMetadata(beanFactory.getBeanDefinition(beanName), bean.getClass());
            metadata.inject(bean, beanName, pvs);
        }
        catch (Throwable ex) {
            throw new BeanCreationException(beanName, "Injection of Scala dependencies failed", ex);
        }
        return pvs;
    }

    private InjectionMetadata findScalaMetadata(BeanDefinition beanDefinition, Class<?> beanClass) throws IntrospectionException {
        LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();

        Set<PropertyValue> scalaProperties = (Set<PropertyValue>) beanDefinition.getAttribute(ScalaAwarePostProcessorUtils.SCALA_ATTRIBUTES_KEY);
        if (scalaProperties != null) {
            for (PropertyValue pv : scalaProperties) {
                Method setter = ScalaAwarePostProcessorUtils.getScalaSetterMethod(beanClass, pv.getName());
                if (setter != null) {
                    Method getter = ScalaAwarePostProcessorUtils.getScalaGetterMethod(beanClass, pv.getName());
                    PropertyDescriptor pd = new PropertyDescriptor(pv.getName(), getter, setter);
                    elements.add(new ScalaSetterMethodElement(setter, pd));
                }
            }
        }
        return new InjectionMetadata(beanClass, elements);
    }

    private class ScalaSetterMethodElement extends InjectionMetadata.InjectedElement {

        protected ScalaSetterMethodElement(Member member, PropertyDescriptor pd) {
            super(member, pd);
        }

        @Override
        protected Object getResourceToInject(Object target, String requestingBeanName) {
            Method method = (Method) this.member;
            MethodParameter methodParam = new MethodParameter(method, 0);
            DependencyDescriptor dd = new DependencyDescriptor(methodParam, true);
            return beanFactory.resolveDependency(dd, requestingBeanName);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

只需在您的上下文中创建这两个 bean:

<bean class="com.other.ScalaAwareBeanFactoryPostProcessor"/>

<bean class="com.other.ScalaAwareBeanPostProcessor"/>
Run Code Online (Sandbox Code Playgroud)

笔记:

这不是最终的解决方案。它适用于类,但不适用于简单类型:

<bean id="beanForInjection" class="com.test.BeanForInjection">
    <property name="bean" ref="beanToBeInjected"/>        
    <property name="name" value="skaffman"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

解决方案适用于bean,但不适用于name。这是可以修复的,但此时我认为您最好使用 @BeanInfo 注释。