在实现RowMapper的类中Spring管理bean注入

时间:2017-05-19 04:11:09

标签: java json spring postgresql inject

我有一个BusinessRowMapper类,它实现了RowMapper,将PostGres JSONB对象转换为Java对象。

BusinessRowMapper implements RowMapper<PersonDetails>

它会覆盖mapRow

   public class BusinessRowMapper implements RowMapper<PersonDetails> {

    private PersonUtility utils;

    public BusinessRowMapper(PersonUtility utils) {
        super();
        this.utils = utils;
    }


    public PersonDetails mapRow(final ResultSet rs, final int rowNum) throws SQLException {
        PersonDetails personDetail = utils.unMarshallAndConvertData(rs
                .getString(ConstantsV4.COLUMN_CUST_DTLS_JSON_DOC));
        return personDetail;
    }
}

现在,如何在此BusinessRowMapper bean中执行Spring托管的PersonUtility Bean注入,而不是将实用程序bean作为构造函数参数传递给BusinessRowMapper?

getNamedParameterJdbcTemplate().query(
                        ConstantsV4.RETRIEVE_PERSON_DETAIL_QUERY, params,
                        new BusinessRowMapper(utility));

1 个答案:

答案 0 :(得分:1)

您可以将@component类定义为在类上添加BusinessRowMapper的spring bean。

然后,您可以在@Component public class BusinessRowMapper implements RowMapper<PersonDetails> { @Autowired private PersonUtility utils; ... }

中自动加载字段
{"date":"2017\/7\/13","student_id":2,"grade":"C"}<br>
{"date":"2017\/7\/1","student_id":3,"grade":"D"}<br>
{"date":"2017\/4\/1","student_id":5,"grade":"E"}