简体   繁体   中英

Spring - change bean definition from XML to annotation

I have a working spring application. Beans are defined in applicationContext.xml.

applicationContext.xml

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

reportFile class

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

@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. How can i make this only with annotations?

The ReportFile class is imported from another own Spring Project.

I am trying to migrate my spring application to spring boot. And i want no more xml configuration.

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 :

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

    /* ...... */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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