0

课程如下:

class ReportControllerBase {
    String reportName = "Report";

    public String getReportName() {
        return reportName;
    }

    public void setReportName(String reportName) {
        this.reportName = reportName;
    }

    // ...
}

class AnnualReportController extends ReportControllerBase {
    // ...
}

class SkinCareAnnualReprotController extends AnnualReportController {
    String productName;

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }
}

基于 XML 的配置如下:

<bean id="annualReportController" class="AnnualReportController">
    <property name="reportName" value="Annual Report"/>
</bean>

<bean id="annualSpecialReportController" class="AnnualReportController">
    <property name="reportName" value="Annual Special Report"/>
</bean>

<bean id="skinCareAnnualReprotController" class="SkinCareAnnualReprotController" parent="annualReportController">
    <property name="productName" value="A famous skin care product"/>
</bean>

Bean AnnualReportControllerAnnualSpecialReportController是同一个 Class 的实例。并且skinCareAnnualReprotController继承自 bean AnnualReportController

如何在 Spring 中基于注解的配置中实现此配置?

4

1 回答 1

1
@Configuration
public class ReportConfiguration {
    @Bean public AnnualReportController annualReportController() {
        AnnualReportController annualReportController = new AnnualReportController();
        annualReportController.setReportName("Annual Report");
        return annualReportController;
    }

     @Bean public AnnualReportController annualSpecialReportController() {
        AnnualReportController annualSpecialReportController = new AnnualReportController();
        return withAnnualSpecialReportName(annualSpecialReportController);
    }

     @Bean public SkinCareAnnualReportController skinCareAnnualReportController() {
        SkinCareAnnualReportController skinCareAnnualReportController = new SkinCareAnnualReportController();
        skinCareAnnualReportController.setProductName("A famous skin care product");
        return withAnnualSpecialReportName(skinCareAnnualReportController);
    }

    // in this instance, a helper method is arguably overkill,
    // but I've included it for demonstration
    private <T extends AnnualReportController> T withAnnualSpecialReportName(T report) {
        report.setReportName("Annual Special Report");
        return report;
    }
}

查看Spring 3.1 文档以获取更多信息。

于 2012-08-05T22:00:29.437 回答