Spring boot里datasource的配置

spring boot里,在包spring-boot-autoconfigure里有个datasource自动配置类

写道
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

 在配置文件application.properties里,配置了spring.datasource.*后,将自动配置datasource

@Conditional(DataSourceAutoConfiguration.NonEmbeddedDataSourceCondition.class)
	@ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
	protected static class NonEmbeddedConfiguration {

		@Autowired
		private DataSourceProperties properties;

		@Bean
		@ConfigurationProperties(prefix = DataSourceProperties.PREFIX)
		public DataSource dataSource() {
			DataSourceBuilder factory = DataSourceBuilder
					.create(this.properties.getClassLoader())
					.driverClassName(this.properties.getDriverClassName())
					.url(this.properties.getUrl()).username(this.properties.getUsername())
					.password(this.properties.getPassword());
			if (this.properties.getType() != null) {
				factory.type(this.properties.getType());
			}
			return factory.build();
		}

	}

 但这里有个条件

@Conditional(DataSourceAutoConfiguration.NonEmbeddedDataSourceCondition.class)

 意思是说,只有存在非嵌入DataSource时才会配置,判定的条件其实是写在DataSourceBuilder里的

private static final String[] DATA_SOURCE_TYPE_NAMES = new String[] {
			"org.apache.tomcat.jdbc.pool.DataSource",
			"com.zaxxer.hikari.HikariDataSource",
			"org.apache.commons.dbcp.BasicDataSource",
			"org.apache.commons.dbcp2.BasicDataSource" };

 也就是说,系统里必须存在上面列举的这些类才可以。

所以如果你在application.properties里配置了spring.datasource.*有关信息后,发现没有datasource的bean,那就说明你可以忘记添加上面这些包了。

虽然spring boot为我们做了很多事情,但是看起来都是偷偷摸摸的,如果对于内部的实现不了解,就可能遇到有时有效,有时无效的情况。

为了安心,也可以自己指定这些配置。

@Configuration
public class DbConfiguration implements TransactionManagementConfigurer {
	
	@Autowired
	private DataSourceProperties properties;
	
	@Bean
	public DataSource dataSource() {
		DataSourceBuilder factory = DataSourceBuilder
				.create(this.properties.getClassLoader())
				.driverClassName(this.properties.getDriverClassName())
				.url(this.properties.getUrl()).username(this.properties.getUsername())
				.password(this.properties.getPassword());
		if (this.properties.getType() != null) {
			factory.type(this.properties.getType());
		}
		return factory.build();
	}

    @Bean
    public PlatformTransactionManager txManager() {
        return new DataSourceTransactionManager(dataSource());
    }

	@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return txManager();
	}

}

 这儿实现了interface:TransactionManagementConfigurer,当有多个事务管理器时,这儿指定默认的用注解声明的事务管理器,比如用Transactional,并未指定transactionManager时。

application.properties

写道
spring.datasource.url=jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource

 当然,你可以不使用DataSourceBuilder,而是直接创建DataSource。

相关推荐