I have three classes and one is a superclass.
class abstract Base {
public abstract String getV();
}
class A extends Base {
private String v;
@Value("${A.v}") public String getV() { return v; };
}
class B extends Base {
private String v;
@Value("${B.v}") public String getV() { return v; };
}
Is there any way to simplify the use of spring @Value annotation? I don't want to copy-paste field declaration and the getter for all Base children. All I get so far is:
class abstract Base {
protected String v;
public String getV() { return v; };
public abstract void setV(String v);
}
class A extends Base {
@Value("${A.v}") public void setV(String v) { this.v = v;};
}
class B extends Base {
@Value("${B.v}") public void setV(String v) { this.v = v;};
}
Is there any more efficient way? Thanks for any help.
I doubt it. Annotations CANNOT be dynamic. There's no way to put any kind of annotation on the abstract setV method which will adapt to the subclass. What you've done is really the right way to go.
However i'd modify your code slightly:
class Base {
private String v;
public String getV() { return v; };
public void setV(String v) { this.v = v; }
}
class A extends Base {
@Value("${A.v}") public String setV(String v) { super.setV(v); }
}
class B extends Base {
@Value("${B.v}") public String setV(String v) { super.setV(v); }
}
I've had this issue not only with @Value annotations, but with @Resource/@Qualifier annotations as well.
This is a big reason i'm not a huge fan of autowiring. I've found myself making a bunch of subclasses for no reason other than to autowire things with different qualifiers/values.
Another alternative might be java based configuration. I know it's not a huge departure from doing it in XML, but i find it cleaner than xml, and certainly better than overriding all your setters.
@Configuration
public class MyConfig {
@Value("${A.v}")
private String av;
@Value("${B.v}")
private String bv;
@Bean
public A a() {
A a = new A();
a.setV(av);
}
@Bean
public B b() {
B b = new B();
b.setV(bv);
}
}
And then in your XML:
<context:annotation-config />
<bean class="MyConfig" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With