spring boot 配置數據源
阿新 • • 發佈:2017-07-14
build -i autowired 1.0 emp aslist private ram apach
以postgreSQL為例,方便下次直接使用。
其中pom.xml引入如下依賴。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.main</groupId> <artifactId>UserManage</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.7.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.0-801.jdbc4</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
在 application.properties 配置數據源
spring.datasource.primary.url=jdbc:postgresql://127.0.0.1:5432/hxquant spring.datasource.primary.username=hxquant spring.datasource.primary.password=hxquant spring.datasource.primary.driver-class-name=org.postgresql.Driver
利用spring加載配置:
@Configuration public classDataSourceConfig { @Bean(name = "primaryDataSource") @Qualifier("primaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource(){ return DataSourceBuilder.create().build(); } @Bean(name = "primaryJdbcTemplate")public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource")DataSource dataSource){ return new JdbcTemplate(dataSource); } }
最後采用 Junit測試效果:
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = UserManageStart.class) public class UserServiceTest { @Autowired @Qualifier("primaryJdbcTemplate") private JdbcTemplate jdbcTemplate1; @Test public void test1(){ List<Map<String,Object>> list = jdbcTemplate1.queryForList("select * from user"); String result = Arrays.asList(list).toString(); System.out.println(result); } }
spring boot 配置數據源