簡體   English   中英

如何在運行時使用bean定義對象生成/創建新的spring bean?

[英]How can I generate/create new spring beans at runtime with a bean definition object?

我是Spring的新手,我想為模板bean寫一個beanGenerator。 我想使用此生成器來解決線程安全問題。 任何人都可以幫助我添加/修改代碼以使其工作嗎? 很難描述我的實際問題,因此我在以下代碼中抽象了該問題:

abstract class BeanDefinition {

  abstract public void preprocess();

}

// now we have 1st user specific bean :
class UserSpecifiedBeanDefinition extends BeanDefinition{

  @override
  public void preprocess() {
     // do something
  }

}


// we could have more user-specific beans that extend BeanDefinition
....




// Following generator class is used to generate beans

public class BeanGenerator {

  private BeanDefinition beanDefinition;
  public BeanGenerator(BeanDefinition beanDefinition) {
    this.beanDefinition = beanDefinition;
  }
  public generate() {
    BeanDefinition newBean = // create new bean based on beanDefinition? how can I make this work??
    newBean.preprocess();
    return newBean;
  }
}

// In spring.xml, I would like to use them like:
<bean id="generator1" class="com.xxx.xxx.BeanGenerator">
    <constructor-arg name="beanDefinition" ref="userSpecifiedBeanDefinition"/>
</bean>

我想您有一個沒有參數的構造函數。 使用反射實例化類

Class c = BeanGenerator.class.getClassLoader().loadClass(beanDefinition.getBeanClassName());
Constructor con = c.getConstructor();
Object instance = con.newInstance();

如果您的構造函數帶有參數,則應更改邏輯以選擇正確的構造函數並將參數傳遞給newInstance()調用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM