spring-boot学习:八、数据库连接之自定义配置
尽管spring boot为我们封装了大量的配置,开箱即用;但是每个项目背景不一样,最归会有一些个性化的需求,比如连接多个数据库,数据库配置需要独立开。以下介绍如何自定义数据库配置。
因为个人习惯,做项目时习惯将数据库配置独立配置到一个单独的文件database.properties中,如:
1. 将配置在application.properties中的数据库配置移入到database.properties(参照上图)
2. 在pom.xml中加入database.properties作为资源文件
<build> <finalName>${name}-${profiles.activation}</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory>src/main/resources</directory> <excludes> <exclude>config/</exclude> </excludes> </resource> <resource> <directory>src/main/resources/config/${profiles.activation}</directory> <filtering>true</filtering> <includes> <include>application.properties</include> <include>database.properties</include> </includes> </resource> </resources> </build>
3. 指定配置文件路径
package com.kevin.springbootstudy; import org.springframework.boot.Banner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.PropertySource; @SpringBootApplication @PropertySource(value={"classpath:database.properties"}) public class SpringBootStudyApplication{ public static void main(String[] args) { SpringApplication app = new SpringApplication(SpringBootStudyApplication.class); app.setBannerMode(Banner.Mode.OFF); app.run(args); } }
4. 运行测试 访问http://127.0.0.1:8081/dbtime返回数据库时间
5. 如果想自定义配置的前缀,比如将spring.datasource.改为app.datasource.
1) database.properties
# mysql app.datasource.url=jdbc:mysql://localhost:3306/springboot2?characterEncoding=utf8&serverTimezone=Asia/Shanghai app.datasource.username=kevin app.datasource.password=123
2) 在Application中定义DataSource
@Bean @ConfigurationProperties(prefix = "app.datasource") public DataSource dataSource(){ return DataSourceBuilder.create().type(HikariDataSource.class).build(); }
3)运行后测试报异常:dataSource or dataSourceClassName or jdbcUrl is required. 意思是需要配置jdbcUrl。将datasource.url改为datasource.jdbc-url,重新测试即可
4)如果使用springboot的默认配置,但是将datasource.url改为datasource.jdbc-url会出现什么?
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).
启动报错,意思就是如果使用默认配置,需要配置datasource.url
总结: 如果使用springboot内置的数据库配置datasource,则需要配置spring.datasource.url,否则需要配置jdbc-url
文档上关于此坑的描述: