1

我需要在一个参数动态传入的方法中实例化一个bean(EmployeeSaver)。我不能使用构造函数设置器,因为这些值在配置时没有填充。

示例代码:

class MyEmployeeBean{
    public void   saveEmployeeDetail (Employee employee , EmployeeHistory hist   ){
        EmployeeDetail detail = hist.getDetail();
        EmployeeSaver eSave = new EmployeeSaver(employee, detail)
        saver.saveEmployee();
    }
}

class EmployeeSaver {

    private Employee empl;
    private EmployeeDetail detail;

    public EmployeeSaver(Employee emp, EmployeeDetail det){

        empl = emp;
        detail = det;
    }

    public void saveEmployee(){
        // code to same the guy...
    }

}

由于 MyEmployeeSaver 类没有默认构造函数,因此它会引发运行时异常。我无法使用以下配置,因为在我执行 hist.getDetail() 之前不知道employeeDetail!

<bean id="mySaverBean" class="come.saver.EmployeeSaver">
    <constructor-arg name="empl" ref="employee" />
    <constructor-arg name="hist" ref = "employeeHistory" />
</bean>  

如何使用构造函数参数实例化employeeSaverBean?

4

1 回答 1

1

您不能直接使用 Spring 配置执行此操作,而是使用ApplicationContext.getBean(String beanName,Object...args)问题中描述的方法。 MyEmployeeBean必须实现ApplicationContextAware访问 Spring 的上下文

class MyEmployeeBean implements ApplicationContextAware {
  ApplicationContext applicationContext;

  void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }

  public void   saveEmployeeDetail (Employee employee , EmployeeHistory hist   ){
        EmployeeDetail detail = hist.getDetail();
        EmployeeSaver eSave = (EmployeeSaver)this.applicationContextnew.getBean("mySaverBean", employee, detail);
        saver.saveEmployee();
    }
}

在 beans.xml 中

<bean id="mySaverBean" class="come.saver.EmployeeSaver" scope="prototype" />

记住 addoscope="prototype"让 Spring 在每次请求时创建一个新实例。

于 2013-08-29T17:59:07.887 回答