1

如何通过spring有条件地初始化一个类?如果某些条件为真,那么我希望传递一个参数,否则传递一些其他参数

<bean id="myFactory" class="Factory">

  if something then
   <constructor-arg>
      <util:map>
        <!-- configure your map here, or reference it as a separate bean -->
        <entry key="java.lang.String" value="key">....</entry>
      </util:map>
   </constructor-arg>
  else
    <constructor-arg>
      <util:map>
        <!-- configure your map here, or reference it as a separate bean -->
        <entry key="java.lang.String" value="key">....</entry>
      </util:map>
   </constructor-arg>
</bean>

如何?

4

2 回答 2

1

Spring Expression Language 可能会为您解决问题。关联

于 2012-08-23T14:23:30.340 回答
0

您可以完全按照您指定的方式进行操作。以这种方式定义FactoryBean,例如。生成客户 Bean:

public class CustomFactoryBean implements FactoryBean<Customer>{

    private int customProperty;

    public int getCustomProperty() {
        return customProperty;
    }

    public void setCustomProperty(int customProperty) {
        this.customProperty = customProperty;
    }

    @Override
    public Customer getObject() throws Exception {
        if (customProperty==1)
            return new Customer("1", "One");        
        return new Customer("999", "Generic");
    }

    @Override
    public Class<?> getObjectType() {
        return Customer.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

基本上就是这样,现在根据你如何注入工厂bean的属性,实际的bean实例化可以在getObject上面的方法中控制

于 2012-08-23T14:33:41.833 回答