【问题标题】:In spring, how to pass objects from one bean to another bean?在春天,如何将对象从一个 bean 传递到另一个 bean?
【发布时间】:2011-09-22 14:27:43
【问题描述】:

我有一个实现 RowMapper 接口的行映射器类。我需要在其中实现 mapRow 方法。它的参数是 ResulSet 和 index。我想在另一个 bean 中使用这个 ResultSet 对象。我怎么去那里?

【问题讨论】:

    标签: spring


    【解决方案1】:

    将此对象设置为实例变量。但我绝不会为 ResultSet 推荐它。结果集在 spring 关闭后将无用(因为 spring 正在管理它)。

    最好从 ResultSet 中提取数据,将数据作为一些模型 bean 存储在实例变量中(但请记住,默认情况下,bean 是单例的,并且对于每次执行,将数据存储为实例变量也没有多大意义)。

    编辑--可以再完善一下,我在这里举个例子

    // this is singleton by default, if you want to store data in this bean
    // mark it as bean either by annotation or thorugh xml
    // so that it can be accessed through spring context
    public class MyBeanRowMapper implements RowMapper
    {
        // you can store something here, 
        // but with each execution of mapRow, it will be updated
        // not recommended to store execution result here
        // or inject other bean here // SomeOtherBean someOtherbean;
    
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            MyBean myBean = new MyBean();
            myBean.setId(rs.getInt("BEAN_ID"));
            myBean.setName(rs.getString("NAME"));
            // set this bean into gloablly accessible object here
            // or to the bean in which you want to access the result
            // something like -->// someOtherBean.setMyBean(myBean)
            // again be careful if someOtherBean is singleton by default
    
            return myBean;
        }
    }
    

    【讨论】:

    • 谢谢库纳尔。现在,我需要配置文件中定义的另一个 bean 中的这个 ResultSet rs 对象。我将以下属性放在写作 bean 我想使用那个 ResultSet 对象在上面(HeaderCopierCallBack)定义的bean
    • 你不应该!映射完成后,ResultSet 将由 spring 关闭。如上例所示,最好将映射对象设置为另一个 bean。
    • 非常感谢。我为此找到了另一种解决方法。不确定它是否正确。我试图管理 bean 中与“headerCallBack”相关的所有内容,再次感谢您的快速响应。
    猜你喜欢
    • 2011-03-11
    • 2014-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 2014-02-21
    相关资源
    最近更新 更多