创建一个类似布线类的弹簧

时间:2011-07-06 14:32:39

标签: spring factory

我想创建一个充当提供者的bean。 我将给它应该返回的类以及在返回之前我应该​​设置的属性列表。

所以基本上它看起来像这样:

<bean id="somethingFactory" class="foo.bar.SomethingFactory">
  <property name="implClass" value="foo.bar.SomehtingImpl" />
  <property name="properties">
    <props>
       <prop key="prop1">prop1Value</prop>
       <prop key="prop2">prop2Value</prop>
     </props>
   </property>
</bean>

“SomethingFactory”有一个provide()方法,它将返回“SomehtingImpl”的实例。

问题是我如何使用Spring来做到这一点?

1 个答案:

答案 0 :(得分:1)

Make SomethingFactory a FactoryBean,扩展AbstractFactoryBeanuse a BeanWrapper以填充输入参数中的属性。

以下是一个示例实现:

public class ServiceFactoryBean<T> extends AbstractFactoryBean<T> {

    private Class<T> serviceType;
    private Class<? extends T> implementationClass;
    private Map<String, Object> beanProperties;


    @Override
    public void afterPropertiesSet() {
        if (serviceType == null || implementationClass == null
                || !serviceType.isAssignableFrom(implementationClass)) {
            throw new IllegalStateException();
        }
    }

    @Override
    public Class<?> getObjectType() {
        return serviceType;
    }

    public void setBeanProperties(final Map<String, Object> beanProperties) {
        this.beanProperties = beanProperties;
    }

    public void setImplementationClass(
        final Class<? extends T> implementationClass) {
        this.implementationClass = implementationClass;
    }

    public void setServiceType(final Class<T> serviceType) {
        this.serviceType = serviceType;
    }

    @Override
    protected T createInstance() throws Exception {
        final T instance = implementationClass.newInstance();
        if (beanProperties != null && !beanProperties.isEmpty()) {
            final BeanWrapper wrapper = new BeanWrapperImpl(instance);
            wrapper.setPropertyValues(beanProperties);
        }
        return instance;
    }

}