开发者

Create a spring like wiring class

I want to create a bean that will act as a provider开发者_如何学Python. I will give it the class that it should return and the list of properties that I should set before returning it.

so basically it looks like this:

<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>

The "SomethingFactory" has a provide() method that will return an instance of "SomehtingImpl".

The question is how can I use Spring to do it?


Make SomethingFactory a FactoryBean, extend AbstractFactoryBean and use a BeanWrapper to populate the properties from the input parameters.

Here's a sample implementation:

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;
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜