Spring和Abstract类 – 在抽象类中注入属性

我有一个抽象的基类,有一个名为“mailserver”的属性,我希望从spring ioc容器中注入。 但是,当我运行抽象类的混凝土实现时,我得到了mailserver属性的null。

这样做的正确方法是什么? 你有没有试过这样做并取得成功? 请分享。

关于khush。

使用abstract属性将抽象基类定义标记为抽象,并在具体类定义中,使parent属性成为抽象类的bean名称的名称

像这样的东西:

        

超类中的属性(抽象与否)与Spring中的任何其他属性完全相同。 您可以使用基于XML,注释或Java配置的setter,构造函数或字段注入。 你可以在Spring中找到广泛使用的inheritance:例如, DefaultMessageListenerContainer 。 展示你如何尝试连接财产,有人可以解释为什么它不起作用。

在我的例子中,在Spring4应用程序中,我不得不使用经典的抽象工厂模式(我从中获取了这个想法 – http://java-design-patterns.com/patterns/abstract-factory/ )来创建实例每次都有一个操作要做。所以我的代码设计如下:

 public abstract class EO { @Autowired protected SmsNotificationService smsNotificationService; @Autowired protected SendEmailService sendEmailService; ... protected abstract void executeOperation(GenericMessage gMessage); } public final class OperationsExecutor { public enum OperationsType { ENROLL, CAMPAIGN } private OperationsExecutor() { } public static Object delegateOperation(OperationsType type, Object obj) { switch(type) { case ENROLL: if (obj == null) { return new EnrollOperation(); } return EnrollOperation.validateRequestParams(obj); case CAMPAIGN: if (obj == null) { return new CampaignOperation(); } return CampaignOperation.validateRequestParams(obj); default: throw new IllegalArgumentException("OperationsType not supported."); } } } @Configurable(dependencyCheck = true) public class CampaignOperation extends EO { @Override public void executeOperation(GenericMessage genericMessage) { LOGGER.info("This is CAMPAIGN Operation: " + genericMessage); } } 

最初为了在抽象类中注入依赖项,我尝试了所有的构造型注释,如@ Component,@ Service等,但即使Spring上下文文件具有整个包的ComponentScanning,但是在创建Subclasses的实例时,例如CampaignOperation,Super Abstract类EO是由于spring无法识别并注入其依赖项,因此其属性为null。经过多次试验和错误,我使用了这个**@Configurable(dependencyCheck = true)**注释,最后Spring能够注入依赖项,我能够使用子类中的属性而不会使它们与太多属性混淆。

   

我也试过这些其他参考资料来找到解决方案:

  1. http://www.captaindebug.com/2011/06/implementing-springs-factorybean.html#.WqF5pJPwaAN
  2. http://forum.spring.io/forum/spring-projects/container/46815-problem-with-autowired-in-abstract-class
  3. https://github.com/cavallefano/Abstract-Factory-Pattern-Spring-Annotation
  4. http://www.jcombat.com/spring/factory-implementation-using-servicelocatorfactorybean-in-spring
  5. https://www.madbit.org/blog/programming/1074/1074/#sthash.XEJXdIR5.dpbs
  6. 使用Spring框架的抽象工厂
  7. Spring Autowiring不适用于抽象类
  8. 在抽象超类中注入spring依赖项
  9. 在抽象类中定义的Spring autowire依赖项
    1. Spring可以在抽象类中自动assembly吗?

请尝试使用**@Configurable(dependencyCheck = true)**并更新此post,如果您遇到任何问题,我可以尝试帮助您。