如何在Spring中将基于XML的配置更改为注释配置?

时间:2012-08-05 17:43:05

标签: spring configuration annotations

课程如下:

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 annualReportController annualSpecialReportController 是同一个Class的实例。 skinCareAnnualReprotController 继承自bean annualReportController

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

1 个答案:

答案 0 :(得分: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 documentation了解详情。