Home > Software design >  How to use constructor injection
How to use constructor injection

Time:03-23

I want to edit this code to use constructor Autowired.

Old code:

@RestController
public abstract class AbstractAccountController<T> {

    @Autowired
    private Service1 service1;
    @Autowired
    private Service2 service2;
    @Autowired
    private Service3 service3;
    
    ...some Java methods
}

child class:

@RestController
public class AccountController extends AbstractAccountController<SomeResource> {

  @Autowired
  private Service4 service4;
  @Autowired
  private Service5 service5;

..... some Java methods
}

I tried to edit the code this way:

@RestController
public abstract class AbstractAccountController<T> {

    private Service1 service1;
    private Service2 service2;
    private Service3 service3;

    @Autowired
    public AccountController(Service1 service1, Service2 service2) {
      this.service1 = service1;
      this.service2 = service2;
    }
    
    ...some Java methods
}

child class:

@RestController
public class AccountController extends AbstractAccountController<SomeResource> {

    private Service3 service3;
    private Service4 service4;
    private Service3 service3;

    @Autowired
    public AccountController(Service3 service3, Service4 service4) {
      this.service3 = service3;
      this.service4 = service4;
    }

    ..... some Java methods
}

But I get error:

There is no default constructor available in 'com.test.controller.AbstractAccountController'

Do you know what would be the best solution?

CodePudding user response:

The error is because the child isn't explicitly calling the parent constructor, so it is assumed the default constructor should be used, but one doesn't exist.

Make sure you call your super constructor from the child:

@Autowired
public AccountController(Service1 service1, Service2 service2, Service3 service3, Service4 service4) {
  super(service1, service2);
  this.service3 = service3;
  this.service4 = service4;
}

CodePudding user response:

AbstractAccount controller does not have constructor in your code. Please change constructor name to AbstractAccountController. If it is typo dont mind it. Also you can simple add final to global variables.

When you extend Abstract class you can pass dependency parameters to abstract class by simply calling super

private final ServiceA serviceA;
public Constructor(ServiceA serviceA){
   super(serviceA);
}
  • Related