2017-08-16 742 views
0

我有一個springboot啓動模塊,它正在讀取一個配置文件並使用該模塊試圖構建任意類型的新bean並將它們添加到bean工廠。通過讀取Springboot啓動模塊中的配置動態註冊Bean

@Configuration 
class SomeConfig implements BeanFactoryAware { 

    BeanFactory beanFactory 

    @Autowired 
    ConfigData configData 

    @Override 
    void setBeanFactory(BeanFactory beanFactory) { 
     this.beanFactory = beanFactory  
    } 

    @PostConstruct 
    void addMoreBeans() { 
     ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory 
     configurableBeanFactory.registerSingleton('someObject', new SomeObject()) 
    } 
} 


@RestController //(in the application) 
class SomeController { 
    @Autowired 
    SomeObject someObject // this is null. 
} 

當我嘗試,其使用含有上述配置豆起動機模塊訪問類型在所述SpringBootApplication「SomeObject」的豆(在控制器豆),它不是自動裝配。

我可以看到,它稍後在啓動過程中初始化了這些bean,但沒有及時讓自動裝配工作。

有沒有辦法強制起動模塊中的bean首先初始化。 ?

+0

我嘗試測試代碼。我發現'BeanFactory'沒有'registerSingleton'方法。我的春天是4.3.10。 – diguage

+0

它是一個** ConfigurableBeanFactory **。上面編輯了我的問題。 – KrishVilay

回答

0

addMoreBeans可能在運行setBeanFactory之前運行。

所以,你可能會寫代碼如下:

@Configuration 
class SomeConfig implements BeanFactoryAware { 

    BeanFactory beanFactory 

    @Autowired 
    ConfigData configData 

    @Override 
    void setBeanFactory(BeanFactory beanFactory) { 
     this.beanFactory = beanFactory 
     beanFactory.registerSingleton('someObject', new SomeObject()  
    } 
} 

@Bean可能是一個更好的辦法。

@Configuration 
class SomeConfig2 { 
    @Bean 
    public SomeObject getSomeObject() { 
     return new SomeObject(); 
    } 
} 
+0

在這種情況下,將拋出一個空指針。它最終確實註冊了,但是沒有及時讓自動裝配在@RestController bean中工作。 – KrishVilay

+0

是的。我的代碼扔了一個空指針。讓我再想一想。 – diguage

+0

第二個選項不適用於我正在查找的內容,因爲我不知道該bean的類型,並且該bean的類型由配置驅動。 – KrishVilay