使用jdbcTemplate需要引入依賴:
<!--jdbc template-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
然后用一個配置類生成JdbcTemplate實例, 交給spring容器
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
//!<1> 注意這里有坑, 看下文!
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password); //totest
dataSource.setInitialSize(10);
return new JdbcTemplate(dataSource);
}
到這里, 啟動, spring會報錯:
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
[解決] autoconfigure需要排除.
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class
})
這時一切貌似美好起來了.
but....'
當你需要使用事務管理時.
按照教程, 使用兩個注解:
@EnableTransactionManagement
@Transactional
然后, 你會碰到:
`PlatformTransactionManager`找不到
這是因為: 參考 Spring Boot 事務的使用
關(guān)于事務管理器,不管是JPA還是JDBC等都實現(xiàn)自接口 PlatformTransactionManager 如果你添加的是 spring-boot-starter-jdbc 依賴硬贯,框架會默認注入 DataSourceTransactionManager 實例日戈。如果你添加的是 spring-boot-starter-data-jpa 依賴腹备,框架會默認注入 JpaTransactionManager 實例胧弛。
因為上文, DataSource是我自己在方法內(nèi)部new的, 沒有交給spring管理, 所以, 它在創(chuàng)建事務管理器時, 由于找不到可用的DataSource, 就不會給我創(chuàng)建了. 這時@Transactional在需要使用事務管理器, 就報找不到了.
徹底解決
- 自己生產(chǎn)DataSource, 交個spring管理
- 若更進一步, 可以自己生產(chǎn)PlatformTransactionManager 實現(xiàn)類(沒有必要了)
@Configuration
@PropertySource("classpath:mysql.properties")
@Slf4j
public class JdbcConf {
@Value("${jdbc.mysql.driver}")
private String driver;
@Value("${jdbc.mysql.url}")
private String url;
@Value("${jdbc.mysql.username}")
private String username;
@Value("${jdbc.mysql.password}")
private String password;
@Bean //聲明其為Bean實例
@Primary //在同樣的DataSource中棋电,首先使用被標注的DataSource
public DataSource dataSource() {
//生成 DataSource
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password); //totest
dataSource.setInitialSize(5);
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
// 其中 dataSource 框架會自動為我們注入
// @Bean
// public PlatformTransactionManager txManager(DataSource dataSource) {
// return new DataSourceTransactionManager(dataSource);
// }
@Bean
public Object testBean(PlatformTransactionManager platformTransactionManager){
log.debug(">>Springboot為本項目注入了事務管理器: " + platformTransactionManager.getClass().getName());
return new Object();
}
}