Spring can you autowire inside an abstract class?

SpringAbstract ClassAutowired

Spring Problem Overview


Spring is failing to autowire my object? Is it possible to autowire an object within an abstract class. Assume all schemas are supplied in application-context.xml

Question: What annotation should be on the base and extending classes (if any) @Service @Component?

Example

abstract class SuperMan {

    @Autowire
    private DatabaseService databaseService;

    abstract void Fly();

    protected void doSuperPowerAction(Thing thing) {

        //busy code

        databaseService.save(thing);

    }
}

Extending class

public class SuperGirl extends SuperMan {

    @Override
    public void Fly() {
        //busy code
    }
 
    public doSomethingSuperGirlDoes() {

        //busy code

        doSuperPowerAction(thing)

    }

application-context.xml

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

Spring Solutions


Solution 1 - Spring

I have that kind of spring setup working

an abstract class with an autowired field

public abstract class AbstractJobRoute extends RouteBuilder {

    @Autowired
    private GlobalSettingsService settingsService;

and several children defined with @Component annotation.

Solution 2 - Spring

Normally, Spring should do the autowiring, as long as your abstract class is in the base-package provided for component scan.

See this and this for further reference.

@Service and @Component are both stereotypes that creates beans of the annotated type inside the Spring container. As Spring Docs state,

> This annotation serves as a specialization of @Component, allowing for > implementation classes to be autodetected through classpath scanning.

Solution 3 - Spring

What if you need any database operation in SuperGirl you would inject it again into SuperGirl.

I think the main idea is using the same object reference in different classes. So what about this:

//There is no annotation about Spring in the abstract part.
abstract class SuperMan {

    
    private final DatabaseService databaseService;

    public SuperMan(DatabaseService databaseService) {
     this.databaseService = databaseService;
    }

    abstract void Fly();

    protected void doSuperPowerAction(Thing thing) {

        //busy code

        databaseService.save(thing);

    }
}

@Component
public class SuperGirl extends SuperMan {

private final DatabaseService databaseService;

@Autowired
public SuperGirl (DatabaseService databaseService) {
     super(databaseService);
     this.databaseService = databaseService;
    }

@Override
public void Fly() {
    //busy code
}

public doSomethingSuperGirlDoes() {

    //busy code

    doSuperPowerAction(thing)

}

In my opinion, inject once run everywhere :)

Solution 4 - Spring

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. https://stackoverflow.com/questions/4042659/using-abstract-factory-with-spring-framework
  7. https://stackoverflow.com/questions/11273070/spring-autowiring-not-working-for-abstract-classes/49203539#49203539
  8. https://stackoverflow.com/questions/4238987/inject-spring-dependency-in-abstract-super-class
  9. https://stackoverflow.com/questions/7184556/spring-and-abstract-class-injecting-properties-in-abstract-classes/49203584#49203584
  10. https://stackoverflow.com/questions/19714586/spring-autowire-dependency-defined-in-an-abstract-class/49203622#49203622

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstackoverflowView Question on Stackoverflow
Solution 1 - SpringFrederic CloseView Answer on Stackoverflow
Solution 2 - SpringAndrei NicusanView Answer on Stackoverflow
Solution 3 - SpringMuhammed OzdoganView Answer on Stackoverflow
Solution 4 - Springuser1295235View Answer on Stackoverflow