在春天,如何将对象从一个bean传递到另一个bean?

时间:2011-09-22 14:27:44

标签: spring

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

1 个答案:

答案 0 :(得分:2)

将此对象设置为实例变量。但我永远不会建议为ResultSet。一旦春天关闭,结果集将无用(因为春天正在管理它)。

更好地从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;
    }
}