Определение бина типа org.springframework.jdbc.core.JdbcTemplate
не найдено, поэтому @Autowired private JdbcTemplate jdbcTemplate;
фактически не имеет значения внутри него.
My 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()));
}
Я понимаю Dependency Injection и IoC, которые должны технически создавать экземпляр JdbcTemplate самостоятельно, но если я делаю это вручную, у меня есть следующий код, который выдает ошибку, что бобу JdbcTemplate
требуется свойство 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);