![](/img/trans.png)
[英]Spring Autowire Bean with multiple Interface Implementations, define Implementation in method
[英]Autowire Spring Bean into interface for default method
我需要向某些类实现的接口添加默认方法,但是我的IDE抱怨( bean may not have been initialized
)。 代码将是这样的:
public interface IValidator {
MyValidationBean beanToBeAutowired;
...
default Boolean doSomeNewValidations(){
return beanToBeAutowired.doSomeNewValidations();
}
}
只是不允许自动装配到接口中还是代码有问题? 在接口上使用@Component
没什么区别。
我宁愿保留这种设计,也不要使用抽象类。
我可以想到的解决方案如下-
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;
}
}
在Java中无法将变量添加到接口中。 默认情况下,它将是public static final
常量。 因此,您必须执行以下任一操作:
MyValidationBean beanToBeAutowired = new MyValidationBeanImpl();
或以下内容:
MyValidationBean beanToBeAutowired();
default Boolean doSomeNewValidations(){
return beanToBeAutowired().doSomeNewValidations();
}
您可以在实现类中重写beanToBeAutowired
方法。
只是一个想法 ,将验证bean
作为parameter
发送到接口;
public interface IValidator {
default Boolean doSomeNewValidations(MyValidationBean beanToBeAutowired){
return beanToBeAutowired.doSomeNewValidations();
}
}
您的callerClass
;
public class CallerClass implements IValidator{
@Autowired
MyValidationBean beanToBeAutowired;
...
doSomeNewValidations(beanToBeAutowired);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.