如何在带有运行时构造函数参数的方法中实例化spring bean? [英] How to Instantiate spring bean with in a method with runtime constructor arguments?

查看:428
本文介绍了如何在带有运行时构造函数参数的方法中实例化spring bean?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to instantiate a bean ( EmployeeSaver) with in a method with parameter coming in dynamically. I can't use constructor setter for these values are not populated at config time.

示例代码:

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!

As MyEmployeeSaver class don't have default constructor so it's throwing runtime exception. I am unsable to use following config as employeeDetail is not know until I do hist.getDetail() !

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

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

How to instantiate employeeSaverBean with constructor arguments?

推荐答案

您无法直接通过Spring配置来执行此操作,而是使用ApplicationContext.getBean(String beanName,Object...args),如本 ApplicationContextAware 访问Spring的上下文

You can't do this directly with Spring configuration, but using ApplicationContext.getBean(String beanName,Object...args) like described in this question. MyEmployeeBean must implements ApplicationContextAware to access Spring's context

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中

and in beans.xml

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

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

Remeber to addo scope="prototype" to let Spring create a new instance at every request.

这篇关于如何在带有运行时构造函数参数的方法中实例化spring bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆