首页 > 解决方案 > 带有接口默认方法的 Spring 属性注入

问题描述

有没有办法在接口默认方法中返回注入的属性?我希望任何实现的类MyInterface都能获得一个getBar()返回属性值的方法,而不必在每个类中重新实现它。我本质上是在尝试做类似的事情

public interface MyInterface {
  String getFoo();

  default String getBar() {
    return @Value("${my.prop.bar}"); //if only
  }
}

通常我只会做一个私有字段并将@Value放在上面,但是接口不能有非常量字段。我认为我可以从接口更改为抽象类并使其工作,但我宁愿作为接口离开,让实现者有机会扩展他们想要的任何东西。

标签: javaspringinterfacepropertiesinject

解决方案


推荐阅读