简体   繁体   English

注释内的 Spring 属性值

[英]Spring property value inside annotation

How can I get property value inside an annotation.如何在注释中获取属性值。 For example I have an annotation例如我有一个注释

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

Now I want "Val1" and 10 to be coming from a property file.现在我希望“Val1”和 10 来自属性文件。 I tried我试过了

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

Which doesn't work.哪个不起作用。

I understand I can use我明白我可以使用

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

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

I don't want that, it need to be inside an annotation.我不想要那个,它需要在注释中。 Any suggestions?有什么建议吗?

In the Spring @Value the replacement of the placeholder is not done inside the annotation but by the framework when inspecting the bean.在 Spring @Value 中,占位符的替换不是在注释内部完成,而是在检查 bean 时由框架完成。

See

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

So, you have to "manually" get the annotation value1 and intVal (which should be a string in your annotation) and resolve them against your properties file.因此,您必须“手动”获取注释 value1 和 intVal(它应该是注释中的字符串)并根据您的属性文件解析它们。

This need involve more code works I think, but maybe you can have a workaround, for example, not hardcode the value for @GetMyValue annonation, just introduce two parameters in a config bean.我认为这需要涉及更多的代码工作,但也许您可以有一个解决方法,例如,不要对@GetMyValue注释的值进行硬编码,只需在配置 bean 中引入两个参数。

private String stringVal;
private int intVal;

then you can use this two params in you annonation by spEL.然后您可以在 spEL 的注释中使用这两个参数。

方法如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM