Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用接口默认方法的Spring属性注入_Java_Spring_Interface_Properties_Inject - Fatal编程技术网

Java 使用接口默认方法的Spring属性注入

Java 使用接口默认方法的Spring属性注入,java,spring,interface,properties,inject,Java,Spring,Interface,Properties,Inject,有没有办法在接口默认方法中返回注入的属性?我希望实现MyInterface的任何类都能获得一个返回属性值的方法getBar(),而不必在每个类中重新实现它。 我基本上是想做一些类似的事情 public interface MyInterface { String getFoo(); default String getBar() { return @Value("${my.prop.bar}"); //if only } } 通常我只需要做一个私有字段并在其上加上@Val

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

public interface MyInterface {
  String getFoo();

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

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

这是组合而不是继承的情况。您所做的基本上与(不鼓励的)仅为常量实现接口的模式是一样的。@chrylis好吧,该接口主要充当契约,并且有许多其他方法。但是实现契约的所有类都需要返回一个属性常量。