27

I've got a pretty simple abstract class

public abstract class AbstractServiceActions {

    @Autowired
    protected DatabaseModel dbModel;

    protected User user;
    protected boolean complete;
    protected String serviceResult;

    public AbstractServiceActions(User user) {
        this.user = user;
        this.serviceResult = "";
    }

    public abstract String doAction();
    }

Now you can see, I'm trying to autowire the DatabaseModel. But in my extended class I only recieve null for the dbModel.

@Component
public class CreateDatabaseAction extends AbstractServiceActions {
....
}

Question: Am I trying something impossible here?

Arsen Davtyan
  • 1,891
  • 8
  • 23
  • 40
onigunn
  • 4,730
  • 10
  • 58
  • 89
  • Are you having spring component-scan the package that your abstract class is in? –  Nov 21 '12 at 07:44

2 Answers2

31

Your setup seems fine. The reason perhaps lies elsewhere. Maybe you are instantiating the class with new CreateDatabaseAction(), rather than letting spring do this.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    +1: Spring allows autowiring in abstract classes, so your suggestion makes good sense! – Espen May 27 '10 at 14:43
  • 2
    @Bozho but how do you let Spring create instance here, constructor of base class expects a parameter, how do you set that in the Annotation? – Spring Jun 09 '15 at 00:01
  • there are many ways to do that. annotations, xml, javaconfig. – Bozho Jun 29 '15 at 16:50
1

Use @Autowired and not @Inject from javax.inject.

Dependency injection in abstract class only works for spring's @Autowired.

FYI, I'm using Spring 4.0; Java 6

TKV
  • 2,533
  • 11
  • 43
  • 56
Viswanath
  • 1,413
  • 13
  • 25