[英]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
). 我需要向某些类实现的接口添加默认方法,但是我的IDE抱怨(
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. 在接口上使用
@Component
没什么区别。
I'd rather keep this design instead of using an abstract class. 我宁愿保留这种设计,也不要使用抽象类。
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;
}
}
Adding a Variable into interface is not possible in Java. 在Java中无法将变量添加到接口中。 It will be by default a
public static final
constant. 默认情况下,它将是
public static final
常量。 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. 您可以在实现类中重写
beanToBeAutowired
方法。
Just an idea , send validation bean
to interface as parameter
; 只是一个想法 ,将验证
bean
作为parameter
发送到接口;
public interface IValidator {
default Boolean doSomeNewValidations(MyValidationBean beanToBeAutowired){
return beanToBeAutowired.doSomeNewValidations();
}
}
Your callerClass
; 您的
callerClass
;
public class CallerClass implements IValidator{
@Autowired
MyValidationBean beanToBeAutowired;
...
doSomeNewValidations(beanToBeAutowired);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.