【发布时间】:2021-04-21 15:42:18
【问题描述】:
我尝试在 MySQL 中创建并自动初始化一个名为“spring”的数据库来存储用户和权限,因此我在“resources”文件夹中创建了文件 schema.sql 和 data.sql(参见下面的脚本)。当我运行程序时,它抛出一个异常,声明“数据源”bean 无法实例化,因为我试图创建的“spring”数据库没有找到!!
PS:程序运行良好,当我切换到内存数据库H2时, 但是当我切换到 MySQL 时,问题如上所述失败。
在我看来,spring boot 正在尝试在执行 MySQL 数据库的 SQL 脚本之前创建“dataSource”bean。
谁能给我解释一下到底发生了什么?
这是涉及数据源 bean 的程序:
package com.javamaster.springsecurityjdbc.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import javax.sql.DataSource;
@Configuration
public class SecurityConfig {
@Bean
public UserDetailsService userDetailsService(DataSource dataSource){
return new JdbcUserDetailsManager(dataSource);
}
@Bean
public PasswordEncoder passwordEncoder(){
return NoOpPasswordEncoder.getInstance();
}
}
schema.sql
create database spring;
CREATE TABLE IF NOT EXISTS `spring`.`users` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(45) NOT NULL,
`password` VARCHAR(45) NOT NULL,
`enabled` INT NOT NULL,
PRIMARY KEY (`id`));
CREATE TABLE IF NOT EXISTS `spring`.`authorities` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(45) NOT NULL,
`authority` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`));
data.sql
INSERT IGNORE INTO `spring`.`authorities` VALUES (NULL, 'tom', 'write');
INSERT IGNORE INTO `spring`.`users` VALUES (NULL, 'tom', '123456', '1');
和application.properties
spring.datasource.url=jdbc:mysql://localhost/spring?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.initialization-mode=always
【问题讨论】:
-
spring.jpa.generate-ddl=true? -
其实我没用JPA,只用JDBC
标签: mysql spring-boot jdbc