更改字符串值的注释
spring或java中是否有注释可以转换给定的字符串?
例如,Spring有注释@Value(“some string”)。如果我不想将“某个字符串”分配给参数/实例变量,而是想分配该字符串的转换值,该怎么办?假设字符串是“foo”。每次我看到这个注释时,我都希望返回的字符串是“bar:foo”而不是foo。我想要的只是能够在参数或实例变量上放置注释,并使该转换自动发生。也许甚至是一个接受类和字符串的注释,以便该类充当给定字符串的转换器。
spring或java中是否有注释可以做到这一点,如果没有,实现这样的事情的最佳方法是什么?
谢谢 劳伦
Is there an annotation in spring or java that transforms a given string?
For example, Spring has the annotation @Value("some string"). What if instead of assigning "some string" to the parameter/instance variable whatever, I want to assign a transformed value of that string. Let's say the string is "foo". Every time I see this annotation I want the string returned to be "bar:foo" and not foo. All I want is to be able to place an annotation over a parameter or instance variable and for that transformation to occur automatically. Perhaps maybe even an annotation that takes a class as well as the string such that the class acts as the transformer for the given string.
Is there an annotation in spring or java that does this and if not what would be the best way to go about implementing such a thing?
Thanks
Lauren
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在
@Value
注释中使用 Spring 表达式语言。这就是您将其用于静态方法的方式:
如果您之前定义了一个 bean,那么您可以简单地使用
@Value("#{bean.method()}")
或@Value("#{bean.property}")
You can use Spring Expression Language inside your
@Value
annotation.This is how you'll use it for a static method:
If you have a bean define previously then you can simply use
@Value("#{bean.method()}")
or@Value("#{bean.property}")
Spring 的
@Value
注释对于使用 Spring 表达式语言将常量以外的值分配给属性非常有用。例如,从属性文件读取的值。如果它所做的只是分配一个常量,您也可以使用private String foo = "bar";
。因此,您可以使用它从某些配置文件或系统属性中获取所需的值。
如果您想要的是将某种转换算法应用于字段,我真的不明白使用注释的意义。只需调用 Java 方法:
这似乎很容易阅读、测试和维护。
The
@Value
annotation of Spring is useful to assign a value other than a constant to a property, using the Spring expression language. For example, a value read from a properties file. If all it did was assigning a constant, you could as well useprivate String foo = "bar";
.So, you might use it to get the value you want from some configuration file or system property.
If what you want is to apply some transformation algorithm to a field, I don't really see the point of using an annotation. Just call a Java method:
That seems easy to read, test and maintain.