29.2 Using JdbcTemplate

Spring的JdbcTemplateNamedParameterJdbcTemplate类是自动配置,你可以直接使用@Autowire注入到你自己的的bean实例中,如以下示例所示:

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.jdbc.core.JdbcTemplate;
  3. import org.springframework.stereotype.Component;
  4. @Component
  5. public class MyBean {
  6. private final JdbcTemplate jdbcTemplate;
  7. @Autowired
  8. public MyBean(JdbcTemplate jdbcTemplate) {
  9. this.jdbcTemplate = jdbcTemplate;
  10. }
  11. // ...
  12. }

您可以使用spring.jdbc.template.*来定制模板的一些属性.如以下示例所示:

  1. spring.jdbc.template.max-rows=500

Note

NamedParameterJdbcTemplate复用了相同的JdbcTemplate实例.如果定义了多个JdbcTemplate且未指定哪个为主,NamedParameterJdbcTemplate将不会自动配置.