Autowire Spring Bean into interface for default method

pablo :

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.

shazin :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=102901&siteId=1
Recommended