注释中的Spring属性值

时间:2016-09-02 05:25:25

标签: java spring spring-annotations

如何在注释中获取属性值。例如,我有一个注释

@GetMyValue(value1="Val1",intVal=10)

现在我想要" Val1"和10来自属性文件。我试过了

@GetMyValue(value1="${test.value}",intVal="${test.int.value}")

哪个不起作用。

我知道我可以使用

@Value("${test.value}")
String value;

@Value("${test.int.value}")
int intValue;

我不想要它,它需要在注释中。有什么建议吗?

3 个答案:

答案 0 :(得分:0)

在Spring @Value中,占位符的替换不是在注释内部完成的,而是在检查bean时由框架完成的。

  • DefaultListableBeanFactory#doResolveDependency
  • DefaultListableBeanFactory#resolveEmbeddedValue
  • org.springframework.util.StringValueResolver

因此,您必须“手动”获取注释value1和intVal(应该是注释中的字符串)并根据属性文件解析它们。

答案 1 :(得分:0)

这需要涉及更多我认为的代码工作,但也许你可以有一个解决方法,例如,不要硬编码@GetMyValue annonation的值,只需在配置bean中引入两个参数。

private String stringVal;
private int intVal;

然后你可以通过spEL在你的公告中使用这两个参数。

答案 2 :(得分:0)

方法如下:

GetMyValue(value1="#{'${test.value}'}",intVal="#{'${test.int.value}'}")