首页 > 解决方案 > 基本 Spring JDBC 应用程序,未找到 JdbcTemplate bean

问题描述

org.springframework.jdbc.core.JdbcTemplate找不到类型的 bean 定义,因此@Autowired private JdbcTemplate jdbcTemplate;它实际上没有值。
我的Application.java如下所示:

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Value("${spring.name}")
private String name;

@Autowired
private JdbcTemplate jdbcTemplate;

private static final Logger log = LoggerFactory.getLogger(Application.class);

//    @Bean
//    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
//        return args -> {
//            System.out.printf("The application is running %s!", name);
//        };
//    }

public void run(String... strings) throws Exception {

    log.info("Creating tables");

    jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
    jdbcTemplate.execute("CREATE TABLE customers(" +
            "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");

    // Split up the array of whole names into an array of first/last names
    List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()
            .map(name -> name.split(" "))
            .collect(Collectors.toList());

    // Use a Java 8 stream to print out each tuple of the list
    splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));

    // Uses JdbcTemplate's batchUpdate operation to bulk load data
    jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames);

    log.info("Querying for customer records where first_name = 'Josh':");
    jdbcTemplate.query(
            "SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[] { "Josh" },
            (rs, rowNum) -> new CustomerModel(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
    ).forEach(customer -> log.info(customer.toString()));
}

我了解依赖注入和 IoC,它们在技术上应该自行实例化 JdbcTemplate 实例,但如果我手动执行它,我将有以下代码给出JdbcTemplatebean 需要dataSource属性的错误(我给出如下):

@Value("${spring.datasource.url}")
private String dbUrl;

@Value("${spring.datasource.username}")
private String dbUsername;

@Value("${spring.datasource.password}")
private String dbPassword;

private DataSource dataSource = new DriverManagerDataSource(dbUrl, dbUsername, dbPassword);

private JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

标签: springspring-jdbc

解决方案


这些行不生产 Spring bean,因此它们不是自动装配的候选者:

private DataSource dataSource = new DriverManagerDataSource(dbUrl, dbUsername, dbPassword);

private JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

如果您使用的是 Spring Boot,则可以按照这些说明配置数据源,但请确保在 pom.xml 中使用 spring-boot-starter-jdbc 依赖项。

如果您手动配置这些,则需要创建一个 @Configuration 类,该类同时公开 DataSource 和 JdbcTemplate bean。例如,类似:

@Configuration
public class DatabaseConfiguration {

   @Value("${spring.datasource.url}")
   private String dbUrl;

   @Value("${spring.datasource.username}")
   private String dbUsername;

   @Value("${spring.datasource.password}")
   private String dbPassword;

   @Bean
   public DataSource dataSource() {
     return new DriverManagerDataSource(dbUrl, dbUsername, dbPassword);
   }

   @Bean
   public JdbcTemplate jdbcTemplate() {
     return new JdbcTemplate(dataSource);
   }
}

推荐阅读