Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring autowire generic type

Spring (from version 4) claims to support generic type injection and I'm trying to do something like this:

public abstract class AbstractControl<T extends IService> {

@Autowired
private T service;

protected T getService(){
    return service;
}

public void setService(T service) {
    this.service = service;
}

}

then an extension of this class:

public class FooControl extends AbstractControl<LoginService> {
}

but Spring is trying to inject IService. Is it possible to inject the inherited type?

like image 229
user6622043 Avatar asked Apr 10 '26 21:04

user6622043


1 Answers

Try moving the @Autowired into the subclass, like this:

  public abstract class AbstractControl<T extends IService> {

    private T service;

    protected T getService(){
        return service;
    }

    public void setService(T service) {
        this.service = service;
    }
  }

And the subclass:

public class FooControl extends AbstractControl<LoginService> {

   @Override
   @Autowired
   public void setService(LoginService service) {
        this.service = service;
    }
}
like image 170
jlumietu Avatar answered Apr 12 '26 12:04

jlumietu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!