在SpringBoot项目新增一个jdbcTemplate数据源
//配置application-dev.yml
spring: datasource1: url: jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Test username: sa password: 123456 driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
package com.example.test.config; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class DataSourceConfig { @Bean @ConfigurationProperties("spring.datasource1") DataSource ds1(){ return DataSourceBuilder.create().build(); } }
package com.example.test.config; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; @Configuration public class JdbcTemplateConfig { @Bean JdbcTemplate jdbcTemplate1(@Qualifier("ds1")DataSource dataSource){ return new JdbcTemplate(dataSource); } }
controller方法调用:
@Resource(name = "jdbcTemplate1")
JdbcTemplate jdbcTemplate1;
等同于:
@Autowired @Qualifier(name = "jdbcTemplate1") JdbcTemplate jdbcTemplate1;