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
You can use Spring Expression Language inside your @Value
annotation.
This is how you'll use it for a static method:
@Value("#{T(fully.qualified.package.name.to.class).getFooString()}")
public void setBar(String value){
this.bar = value;
}
If you have a bean define previously then you can simply use
@Value("#{bean.method()}")
or @Value("#{bean.property}")
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 use private 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:
@Value("foo") // or some EL expression which evaluates to "foo"
public void setBar(String value) {
this.bar = someStringTransformer.transform(value);
}
That seems easy to read, test and maintain.
精彩评论