Pablo Fradua
Pablo Fradua

Reputation: 389

Autowire Spring Bean into interface for default method

I need to add a default method to an interface some classes implement, but my IDE complains (bean may not have been initialized). Code would be something like this:

public interface IValidator {

    MyValidationBean beanToBeAutowired;
    ...
    default Boolean doSomeNewValidations(){
        return beanToBeAutowired.doSomeNewValidations();
    }
}

Is it just that autowiring into interfaces is not allowed or there's something wrong with the code? Using @Component on the interface doesn't make any difference.

I'd rather keep this design instead of using an abstract class.

Upvotes: 12

Views: 16717

Answers (3)

drowny
drowny

Reputation: 2147

Just an idea, send validation bean to interface as parameter;

public interface IValidator {

    default Boolean doSomeNewValidations(MyValidationBean beanToBeAutowired){
        return beanToBeAutowired.doSomeNewValidations();
    }
}

Your callerClass;

public class CallerClass implements IValidator{

    @Autowired
    MyValidationBean beanToBeAutowired;
    ...

    doSomeNewValidations(beanToBeAutowired);

}

Upvotes: 3

Amit Naik
Amit Naik

Reputation: 1073

i can think of solution as below -

public interface IValidator {

   public Service getBeanToBeAutowired();

   default Boolean doSomeNewValidations(){
    return getBeanToBeAutowired().doSomeNewValidations();
   }

}

public class ValidatorClass implements IValidator {

    @Autowire private Service service;

    @Override
    public Service getBeanToBeAutowired() {
        return service;
    }

}

Upvotes: 8

shazin
shazin

Reputation: 21883

Adding a Variable into interface is not possible in Java. It will be by default a public static final constant. So you have to do either the following:

MyValidationBean beanToBeAutowired = new MyValidationBeanImpl();

or the following:

MyValidationBean beanToBeAutowired();

default Boolean doSomeNewValidations(){
    return beanToBeAutowired().doSomeNewValidations();
}

And you can override the beanToBeAutowired method in the implementation class.

Upvotes: 5

Related Questions