我正在尝试创建 JdbcTemplate bean,如下所示:
@Configuration
public class ServiceBeanConfiguration {
@Bean
public JdbcTemplate jdbcTemplate() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setDriverClassName("org.postgresql.Driver");
driverManagerDataSource.setUrl("jdbc:postgresql://localhost:5432/sp");
driverManagerDataSource.setUsername("posthres");
driverManagerDataSource.setPassword("password");
DataSource dataSource = driverManagerDataSource;
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
我将此 @Bean Autowiring 到我的服务类中。但结果我收到错误:
**************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
最佳答案
创建一个application.properties
并将spring.datasource
属性放入其中。
spring.datasource.url=jdbc:postgresql://localhost:5432/sp
spring.datasource.username=postgres
spring.datasource.password=password
删除您的ServiceBeanConfiguration
并重新启动您的应用程序。
Spring Boot 将自动为您配置 DataSource
和 JdbcTemplate
。
关于java - JdbcTemplate 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51985986/