如何在运行时构造函数参数的方法中实例化spring bean?

时间:2013-08-29 16:59:50

标签: spring inversion-of-control

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

示例代码:

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?

1 个答案:

答案 0 :(得分:2)

您不能直接使用Spring配置执行此操作,而是使用此question中所述的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" />

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