【问题标题】:How to pass current Connection from Spring context to iReport?如何将当前连接从 Spring 上下文传递到 iReport?
【发布时间】:2014-12-22 14:31:07
【问题描述】:

我想从 Spring 上下文中获取当前连接,然后传递给我的 JasperPrint 对象。

类似这样的:

 //java.sql.Connection con = StringContext.getConnection();
 JasperPrint jp = JasperFillManager.fillReport("reports/my_report.jasper", parameters, con);

我怎样才能使它工作?

ps:我尝试过使用DataSourceUtils,但是getConnection()方法需要一个DataSource对象作为参数,我从哪里得到这个对象?

【问题讨论】:

  • 使用DataSourceUtils,但我建议您查看 Spring 中的 Jasper 支持,这可能会给您一些其他见解。
  • @M.Deinum ,但是该怎么做呢? DataSourceUtils.getConnection()方法需要一个DataSource参数,这个参数哪里来?
  • 你可以在你创建JasperPrint的类中注入DataSource(我假设那是一个spring管理的类)。

标签: java spring jasper-reports


【解决方案1】:

你可能需要这样的东西:

@Component
class JRExporter{
    @Autowired
    protected DataSource localDataSource;

    public void export(){
      java.sql.Connection con = localDataSource.getConnection()
      JasperPrint jp = JasperFillManager.fillReport("reports/my_report.jasper", parameters, con);
    }

【讨论】:

  • 但是JRExporter必须是Spring组件
  • 我正在使用 Hikari 数据源,当我如图所示自动连接数据源时,getConnection() 每次调整报告时都会出现连接泄漏错误
【解决方案2】:

最好的方法是使用当前事务的连接(这里显示https://stackoverflow.com/a/8428795/6230007),使用DataSourceUtils.getConnection()

@Autowired
private ApplicationContext applicationContext; 
...

JasperPrint jp = JasperFillManager.fillReport("my_report.jasper", params,
DataSourceUtils.getConnection((DataSource)applicationContext.getBean("dataSource")));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多