spring - 基本 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 实例,但如果我手动执行它,我将有以下代码给出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);
解决方案
这些行不生产 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);
}
}
推荐阅读
- postgresql - 有没有办法在 PostgreSQL 上使用带有 btree 索引的 pg_trgm 运算符?
- rxjs - 只有在使用 Pipeable Operators 时才有副作用?
- vba - 读取单元格日期时出错
- python - 停止在气流中执行剩余任务
- node.js - 保存 gpg 或 gpg2 的密码
- c# - 访问创建的文件 C#
- graphql - 如何影响 GraphQL 中的父结果?
- python - 用 NaN 替换列表中的空字符串
- python - PyQt5 - 如何通过连接到 QLabel 的 linkActivated 信号的方法传递链接?
- react-native - React Native Google 登录问题