2016-07-18 62 views
0

我有一個由2個項目組成的應用程序 - UI和數據。在數據項目中,我已經添加了一個彈簧豆到XML應用程序上下文:春豆注入 - bean定義後注入屬性

<bean id="mail-notification-service" class="com.test.DefaultEmailNotificationManager"> 
    </bean> 

此管理器發出通知要求,參數使用一個簡單的枚舉和參數對象(兩者都使用類只在數據項目中)選擇一個IEmailGenerator並使用它發送電子郵件。

經理的定義是這樣的:

public class DefaultEmailNotificationManager implements IEmailNotificationManager { 
    public MailResult sendEmail(EmailType type) { .. } 
    public void register(IEmailGenerator generator) { .. } 
} 

public interface IEmailGenerator { 
    public EmailType getType(); 
} 

麻煩的是,該發電機在UI項目中定義,這樣他們就可以做這樣的事情讓檢票頁面類,請求週期,和應用資源的保持。因此我不能將它們添加到數據項目的applicationContext中的bean中,以便數據和UI項目中的其他模塊都可以使用它們。

有沒有在UI項目做類似的ApplicationContext的任何方式:

<bean id="exclusionNotifier" class="com.test.ui.ExclusionEmailNotifier"/> 
<bean id="modificationNotifier" class="com.test.ui.ModificationEmailNotifier"/> 

<call-method bean-ref="mail-notification-service" method="register"> 
    <param name="generatorImplementation", ref="exclusionNotifier"/> 
</call-method> 

<call-method bean-ref="mail-notification-service" method="register"> 
    <param name="generatorImplementation", ref="modificationNotifier"/> 
</call-method> 

我可以手動在WicketApplication.init方法扳平豆在一起,但會喜歡的東西更優雅。有沒有人做過這樣的事情?

使用Spring提前4.1.4

感謝。

回答

1

進樣發電機到mail-notification-service豆(例如使用autowire="byType"),並使用init-method豆施工後立即註冊(見春文檔Initialization callbacks

public class DefaultEmailNotificationManager implements IEmailNotificationManager { 
    private Collection<IEmailGenerator> generators; 
    public void init() { 
    for(IEmailGenerator g : generators) { 
     register(g); 
    } 
    } 
    public void setGenerators(Collection<IEmailGenerator> generators) { 
    this.generators = generators; 
    } 
    public MailResult sendEmail(EmailType type) { .. } 
    private void register(IEmailGenerator generator) { .. } 
} 

數據的的applicationContext:

<bean id="mail-notification-service" 
     class="com.test.DefaultEmailNotificationManager" 
     init-method="init" 
     autowire="byType" /> 

UI的的applicationContext:

<bean id="exclusionNotifier" class="com.test.ui.ExclusionEmailNotifier"/> 
<bean id="modificationNotifier" class="com.test.ui.ModificationEmailNotifier"/> 
+0

嗨,謝謝你的回覆。我嘗試過,但在init方法中獲得了NPE - 未設置生成器。 – fancyplants

+1

我已經更新了答案。使用基於setter的方式注入'generators'字段。 –

+0

謝謝,這使它工作!春季文檔只能說這可以在這裏完成:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-autowire - 在別處他們聲明如果不止一個bean匹配,那麼它會失敗。即使表7.2中的鏈接也說明,在指南之前在段落中糾正自己! – fancyplants