Reputation: 852
I've a base class with a property that should be set in the derived class. I've to use annotations. How's that possible? I know how do this with xml spring configurations, but not with annotations, because I've to write them at the property?
Here's some example code:
public class Base {
// This property should be set
private String ultimateProperty;
// ....
}
public class Hi extends Base {
// ultimate property should be "Hi" in this class
// ...
}
public class Bye extends Base {
// ultimate property should be "Bye" in this class
// ...
}
How is this possible with annotations?
Upvotes: 1
Views: 4435
Reputation: 128779
Some options depending on what else Base has:
class Base {
private String ultimateProperty;
Base() {
}
Base(String ultimateProperty) {
this.ultimateProperty = ultimateProperty;
}
public void setUltimateProperty(String ultimateProperty) {
this.ultimateProperty = ultimateProperty;
}
}
class Hi extends Base {
@Value("Hi")
public void setUltimateProperty(String ultimateProperty) {
super.setUltimateProperty(ultimateProperty);
}
}
class Bye extends Base {
public Bye(@Value("Bye") String ultimateProperty) {
setUltimateProperty(ultimateProperty);
}
}
class Later extends Base {
public Later(@Value("Later") String ultimateProperty) {
super(ultimateProperty);
}
}
class AndAgain extends Base {
@Value("AndAgain")
private String notQuiteUltimate;
@PostConstruct
public void doStuff() {
super.setUltimateProperty(notQuiteUltimate);
}
}
Of course, if you really just want the name of the class there, then
class SmarterBase {
private String ultimateProperty = getClass().getSimpleName();
}
Upvotes: 2
Reputation: 2611
Annotations for fields are linked directly to the source code in the class. You may be able to do what you are looking for via Spring EL with-in an @Value annotation, but I think the complexity overrides the value.
A pattern you may want to consider is using @Configuration annotation to programmatically setup your application context. That way you can define what is injected into the base class.
Upvotes: 0