Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在带有spring注释的派生类中设置基类的属性_Java_Spring_Annotations - Fatal编程技术网

Java 在带有spring注释的派生类中设置基类的属性

Java 在带有spring注释的派生类中设置基类的属性,java,spring,annotations,Java,Spring,Annotations,我有一个基类,其属性应该在派生类中设置。我必须使用注释。怎么可能呢? 我知道如何使用XMLSpring配置,但不知道如何使用注释,因为我必须在属性中编写它们 下面是一些示例代码: public class Base { // This property should be set private String ultimateProperty; // .... } public class Hi extends Base { // ultimate prope

我有一个基类,其属性应该在派生类中设置。我必须使用注释。怎么可能呢? 我知道如何使用XMLSpring配置,但不知道如何使用注释,因为我必须在属性中编写它们

下面是一些示例代码:

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

注释如何实现这一点?

字段的注释直接链接到类中的源代码。您可能可以通过Spring EL在@Value注释中实现所需的功能,但我认为复杂性会覆盖该值


一个您可能要考虑的模式是使用@配置注释来以编程方式设置应用程序上下文。通过这种方式,您可以定义注入基类的内容。

一些选项取决于基类的其他内容:

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

有没有理由不在构造函数中调用setter?
私有字符串ultimateProperty
不是属性,而是字段。在这样的问题中,术语很重要。您是指字段还是指属性(即具有getter和/或setter)?