Spring bean注入 - 在定义bean之后注入属性

时间:2016-07-18 14:49:50

标签: java spring wicket-6

我有一个由2个项目组成的应用程序 - UI和数据。在Data项目中,我在xml应用程序上下文中添加了一个spring 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项目中定义的,因此他们可以执行诸如获取wicket页面类,请求周期和应用程序资源之类的事情。因此,我无法在数据项目中将它们添加到bean中。 applicationContext,以便数据和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方法中手动绑定bean,但更喜欢更优雅的东西。有人做过这样的事吗?

使用Spring 4.1.4

提前致谢。

1 个答案:

答案 0 :(得分:1)

将生成器注入mail-notification-service bean(例如使用autowire="byType")并在使用init-method构建bean之后立即注册它们(请参阅Spring文档中的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 ) { .. }
}

data的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"/>
相关问题