【问题标题】:Spring - change bean definition from XML to annotationSpring - 将 bean 定义从 XML 更改为注释
【发布时间】:2018-03-01 13:56:18
【问题描述】:

我有一个有效的 spring 应用程序。 bean 在 applicationContext.xml 中定义。

applicationContext.xml

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

报告文件类

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

在 java 类中的用法

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

这很好用。但现在我想在 xml 中使用 bean 声明。我怎样才能只用注释来做这个?

ReportFile 类是从另一个自己的 Spring 项目中导入的。

我正在尝试将我的 Spring 应用程序迁移到 Spring Boot。而且我不需要更多的 xml 配置。

可能的解决方案:

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

【问题讨论】:

  • 将其添加为 @Bean 在您的 @Configuration 类中
  • 或者在类声明中添加@Component("reportFileA")。但不知道该物业。
  • 我理解正确吗?见上文(可能的解决方案)

标签: java spring spring-boot


【解决方案1】:

为了将资源注入您的 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;
    }      

    /* ...... */
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 2023-04-01
    • 2017-02-18
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    相关资源
    最近更新 更多