Basic Spring JDBC应用程序,找不到JdbcTemplate bean

时间:2018-04-25 15:22:06

标签: spring spring-jdbc

找不到类型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实例,但如果我手动实现它,我有以下代码,它给出了JdbcTemplate bean需要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);

1 个答案:

答案 0 :(得分:1)

这些行不会产生Spring bean,因此它们不适合自动装配:

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

private JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

如果您正在使用Spring Boot,则可以follow these instructions配置数据源,但请确保在pom中使用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);
   }
}