简体   繁体   中英

Spring autowire dependency defined in an abstract class

I have an abstract class "Command" with an @Autowired dependency and classes extending the abstract class. The dependency is not being injected. The abstract and concrete classes are annotated with @Component and are being scanned. It seems that the base(abstract) class is not spring managed. What needs to be done for it to be? Is there an annotation to define it as abstract? I don't want to define the bean in XML.

public abstract class Command {
  @Autowired
  private SecurityUtils securityUtils;
....

@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
@Component
public class NoteCommand extends Command {
...
}

My mistake I apologize. The command classes are injected in my controllers and one of them (NoteCommand) out many was instantiated manually via "new". All is good.

This can be achieved with XML configuration(not sure about annotations). Read this http://docs.spring.io/spring-framework/docs/3.0.0.RC3/reference/html/ch03s07.html

Try this(add other config to child bean?)

<bean id = "command" class = "some.package.name.Command" abstract = "true">
  <property name = "securityUtils" ref = "securityUtils"/>
</bean>

<bean id ="noteCommand" class = "some.package.name.NoteCommand" parent="commadn">

</bean>

cheers!

In my case, inside a Spring4 Application, i had to use a classic Abstract Factory Pattern(for which i took the idea from - http://java-design-patterns.com/patterns/abstract-factory/ ) to create instances each and every time there was a operation to be done.So my code was to be designed like:

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);
    }
}

Initially to inject the dependencies in the abstract class I tried all stereotype annotations like @Component, @Service etc but even though Spring context file had ComponentScanning for the entire package, but somehow while creating instances of Subclasses like CampaignOperation, the Super Abstract class EO was having null for its properties as spring was unable to recognize and inject its dependencies.After much trial and error I used this **@Configurable(dependencyCheck = true)** annotation and finally Spring was able to inject the dependencies and I was able to use the properties in the subclass without cluttering them with too many properties.

<context:annotation-config />
<context:component-scan base-package="com.xyz" />

I also tried these other references to find a solution:

  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. Using abstract factory with Spring framework
  7. Spring Autowiring not working for Abstract classes
  8. Inject spring dependency in abstract super class
  9. Spring and Abstract class - injecting properties in abstract classes
    1. Spring can you autowire inside an abstract class?

Please try using **@Configurable(dependencyCheck = true)** and update this post, I might try helping you if you face any problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM