springboot项目嵌入式数据库驱动程序配置及使用方法
    		       		warning:
    		            这篇文章距离上次修改已过427天,其中的内容可能已经有所变动。
    		        
        		                
                
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.jdbc.DataSourceBuilder;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
 
@Configuration
public class DatabaseConfig {
 
    @Value("${spring.datasource.url}")
    private String dbUrl;
 
    @Value("${spring.datasource.username}")
    private String username;
 
    @Value("${spring.datasource.password}")
    private String password;
 
    @Bean
    public DataSource dataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(dbUrl);
        dataSourceBuilder.username(username);
        dataSourceBuilder.password(password);
        return dataSourceBuilder.build();
    }
}这段代码定义了一个配置类DatabaseConfig,它使用Spring Boot的DataSourceBuilder来创建一个数据源。@Value注解用于注入数据库的URL、用户名和密码,这些值通常在application.properties或application.yml配置文件中定义。dataSource方法使用DataSourceBuilder创建了一个数据源,并通过方法注解@Bean将其注册为Spring应用上下文中的一个Bean。这样,你就可以在其他Spring组件中通过依赖注入的方式来使用这个数据源了。
评论已关闭