2011-04-05 57 views
0

我有一個單例類,我想用Spring的IoC創建。這個類需要使用IoC來實例化其他對象的動態數量。因此,這個類需要傳入的作爲構造函數參數的BeanFactory。我怎樣才能做到這一點?如何提供當前BeanFactory作爲構造函數參數

這是我計劃的一般結構。我對Spring IoC相當陌生,所以如果它在Spring中不適合,我也願意改變這個結構。

public class Main 
{ 
    public static void main(String[] args) 
    { 
     ApplicationContext context = 
       new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"}); 

     MySingletonInterface instance = context.getBean(MySingletonInterface.class); 

     instance.foo(); 
    } 
} 

public class MySingletonClass implements MySingletonInterface 
{ 
    public MySingletonClass(BeanFactory beanFactory) 
    { 
     this.beanFactory = beanFactory; 
    } 

    public void foo() 
    { 
     for(.....) 
     { 
      NeedManyInstances instance = beanFactory.getBean(NeedManyInstances.class); 
      .... 
     } 
    } 
} 

回答

2

最簡單的方法是聲明構造爲@Autowired(確保應用程序上下文is configured for use of annotation-based configuration<context:annotation-config/>):

@Autowired 
public MySingletonClass(BeanFactory beanFactory) { ... } 

另一種選擇是讓你的類實現BeanFactoryAware和使用setBeanFactory()方法,而不是構造函數。

+0

BeanFactoryAware解決方案運行良好。謝謝! – 2011-04-05 19:10:42

相關問題