![](/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.