【问题标题】:How to get the MySQL connection from applicaiton.properties in spring boot ireport如何在spring boot ireport中从applicaiton.properties获取MySQL连接
【发布时间】:2023-03-25 21:54:01
【问题描述】:

目前我正在使用此代码生成 ireport。但是我需要直接从 application.properties 获取数据源,因为我不想再次使用用户名和密码进行 sql 连接。

        File file = ResourceUtils.getFile("classpath:report/collectorInvoice.jrxml");
        InputStream input = new FileInputStream(file);

        // Compile the Jasper report from .jrxml to .japser
        JasperReport jasperReport = JasperCompileManager.compileReport(input);

        conn = DriverManager.getConnection("jdbc:mysql://localhost/divron?createDatabaseIfNotExist=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","aha","123");

        // Get the parameter
        Map<String, Object> parameters = new HashMap<>();

        parameters.put("invoiceId",id);
        try (Connection connection = dataSource.getConnection()) {

            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);

            // Export the report to a PDF file
            JasperExportManager.exportReportToPdfFile(jasperPrint, "D://" +"collectorInvoice -"+ id + ".pdf");

        }
        return new ResponseEntity<Object>(null, HttpStatus.OK);

这是应该更改的代码。

        conn = DriverManager.getConnection("jdbc:mysql://localhost/divron?createDatabaseIfNotExist=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","aha","123");

所以请帮我从sql连接中获取全部数据,而无需再次使用sql连接的用户名和密码。

【问题讨论】:

    标签: java spring jdbc datasource


    【解决方案1】:

    如果 Spring Boot 已经创建了 DataSource,您可以在 Bean 中自动装配它(或使用其他注入方式)并使用来自 DataSource 的连接

    @Autowired
    DataSource dataSource;
    ....
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource.getConnection());
    

    【讨论】:

    • 非常感谢.. 对我来说,我已经添加了@Autowired @Qualifier("dataSource") private DataSource dataSource;并且工作正常
    猜你喜欢
    • 2020-07-12
    • 2017-11-13
    • 1970-01-01
    • 2021-03-20
    • 2018-06-09
    • 2018-08-19
    • 2019-08-10
    • 2019-12-03
    • 2019-07-20
    相关资源
    最近更新 更多