有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何通过spring有条件地初始化类

如何通过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>

怎么做


共 (2) 个答案

  1. # 1 楼答案

    你可以完全按照你指定的方式来做。以这种方式定义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的属性,可以在上面的getObject方法中控制实际的bean实例化

  2. # 2 楼答案

    Spring表达式语言可能会对您有所帮助link