【问题标题】:Autowire Spring Bean into interface for default method将 Spring Bean 自动装配到默认方法的接口中
【发布时间】:2018-10-03 07:07:27
【问题描述】:

我需要向某些类实现的接口添加默认方法,但我的 IDE 抱怨 (bean may not have been initialized)。 代码是这样的:

public interface IValidator {

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

只是不允许自动装配到接口中还是代码有问题? 在界面上使用@Component没有任何区别。

我宁愿保留这个设计而不是使用抽象类。

【问题讨论】:

  • 接口中的依赖注入不起作用,因为您无法实例化接口,因此您将无法注入任何东西。
  • 在实现类中使用注解。

标签: java spring spring-boot


【解决方案1】:

在 Java 中无法将变量添加到接口中。默认情况下,它将是 public static final 常量。因此,您必须执行以下任一操作:

MyValidationBean beanToBeAutowired = new MyValidationBeanImpl();

或以下:

MyValidationBean beanToBeAutowired();

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

而且你可以覆盖实现类中的beanToBeAutowired方法。

【讨论】:

  • 感谢您的建议,但切换到抽象类会更简洁(在我的情况下)。
【解决方案2】:

我可以想到以下解决方案 -

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;
    }

}

【讨论】:

  • 我也在想同样的事情......我建议为这个答案提供一个基本的实现来展示它是如何工作的
  • 与 shazin 的回答相同,可以,但在我的情况下切换到抽象类更容易。感谢您的输入
【解决方案3】:

只是一个想法,以parameter 的身份将验证bean 发送到接口;

public interface IValidator {

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

你的callerClass;

public class CallerClass implements IValidator{

    @Autowired
    MyValidationBean beanToBeAutowired;
    ...

    doSomeNewValidations(beanToBeAutowired);

}

【讨论】:

    猜你喜欢
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    • 2015-08-04
    • 1970-01-01
    • 2012-12-04
    • 2014-06-06
    相关资源
    最近更新 更多