29.2 Using JdbcTemplate
Spring的JdbcTemplate
和NamedParameterJdbcTemplate
类是自动配置,你可以直接使用@Autowire注入到你自己的的bean实例中,如以下示例所示:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
private final JdbcTemplate jdbcTemplate;
@Autowired
public MyBean(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// ...
}
您可以使用spring.jdbc.template.*来定制模板的一些属性.如以下示例所示:
spring.jdbc.template.max-rows=500
Note
NamedParameterJdbcTemplate
复用了相同的JdbcTemplate
实例.如果定义了多个JdbcTemplate
且未指定哪个为主,NamedParameterJdbcTemplate
将不会自动配置.