2011-07-06 32 views
0

我想創建一個將充當提供者的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」有將返回「SomehtingImpl」的一個實例提供()方法。

問題是我該如何使用Spring來做到這一點?

回答

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

} 
+0

非常感謝您的回答 - 這正是我需要的 –