2011-08-08 43 views
1

我有一个基类,应该在派生类中设置属性。我必须使用注释。那可能怎么样? 我知道如何做到这一点与XML弹簧配置,但没有注释,因为我要写在属性?在派生类中设置基类的属性,使用弹簧注释

下面是一些示例代码:

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 
    // ... 
} 

这怎么可能与注解?

+2

任何理由不只是调用的setter在你的构造函数中? –

+0

'private String ultimateProperty'不是一个属性,它是一个字段。术语在这些问题中很重要。你的意思是一个领域,还是你的意思是一个属性(即与getter /和/或setter)? – skaffman

回答

2

取决于什么其他基地的一些选项有:

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); 
    } 
} 

当然,如果你真的只是想在班上有名称,然后

class SmarterBase { 
    private String ultimateProperty = getClass().getSimpleName(); 
} 
0

字段注释直接链接到类中的源代码。您可能能够通过Spring EL使用@Value注释来执行您正在寻找的内容,但我认为复杂性会覆盖该值。

您可能要考虑的模式是使用@Configuration注释以编程方式设置您的应用程序上下文。这样你可以定义什么被注入到基类中。

相关问题