简体   繁体   English

Spring - 将bean定义从XML更改为注释

[英]Spring - change bean definition from XML to annotation

I have a working spring application. 我有一个弹簧应用程序。 Beans are defined in applicationContext.xml. Bean在applicationContext.xml中定义。

applicationContext.xml applicationContext.xml中

<bean name="reportFileA" class="com.xyz.ReportFile">
        <property name="resource" value="classpath:documents/report01.rptdesign" />
</bean> 

reportFile class reportFile类

public class ReportFile {

private File file;

public void setResource(Resource resource) throws IOException {
    this.file = resource.getFile();
}

public File getFile() {
    return file;
}

public String getPath() {
    return file.getPath();
}
}

usage in a java class 在java类中的用法

@Resource(name = "reportFileA")
@Required
public void setReportFile(ReportFile reportFile) {
    this.reportFile = reportFile;
}

This works fine. 这很好用。 But now i want to get ride of the bean declartion in xml. 但现在我想在xml中获取bean声明。 How can i make this only with annotations? 我怎么能用注释做这个?

The ReportFile class is imported from another own Spring Project. ReportFile类是从另一个自己的Spring Project导入的。

I am trying to migrate my spring application to spring boot. 我正在尝试将我的spring应用程序迁移到spring boot。 And i want no more xml configuration. 我不想再有xml配置了。

Possible Solution: 可能解决方案

@Bean(name="reportFileA")
public ReportFile getReportFile() {
    ReportFile report = new ReportFile();
    try {
        report.setResource(null);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return report;
}

In order to inject the Resource to your bean use the ResourceLoader , Try the below code : 要将Resource注入您的bean,请使用ResourceLoader ,请尝试以下代码:

@Configuration
public class MySpringBootConfigFile {
    /*.....  the rest of config */

    @Autowired
    private ResourceLoader resourceLoader;

    @Bean(name = "reportFileA")
    public ReportFile reportFileA() {
        ReportFile reportFile = new ReportFile();
        Resource ressource = resourceLoader.getResource("classpath:documents/report01.rptdesign");
        try {
            reportFile.setResource(ressource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reportFile;
    }      

    /* ...... */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM