通常、spring-bootでデータソースを定義するには以下のようにプロパティ等で設定するが、従来のように@Bean
で定義も出来る。
spring.datasource.url=jdbc:postgresql://192.168.10.23:5432/testdb
spring.datasource.username=postgres
spring.datasource.password=xxxx
ソースコード
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<properties>
<java.version>10.0</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
以下のように、DataSource
を返す@Bean
定義を作っておけばそれを使ってくれる。ここではとりあえずの動作確認にPostgreSQLのPGSimpleDataSource
を使用している。
import javax.sql.DataSource;
import org.postgresql.ds.PGSimpleDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
@SpringBootApplication
public class App implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(App.class, args).close();
}
@Autowired
JdbcTemplate t;
@Bean
public DataSource dataSource() {
PGSimpleDataSource p = new PGSimpleDataSource();
p.setUrl("jdbc:postgresql://192.168.10.23:5432/testdb");
p.setUser("postgres");
p.setPassword("xxxx");
return p;
}
@Override
public void run(String... args) throws Exception {
t.query("select * from users", (e) -> {
System.out.println(e.getInt("user_id"));
});
}
}
バリエーションとして@ConfigurationProperties
でプロパティをファイル等から読み込む方法もある。
my.datasource.postgres.url=jdbc:postgresql://192.168.10.23:5432/testdb
my.datasource.postgres.user=postgres
my.datasource.postgres.password=xxxx
@ConfigurationProperties(prefix = "my.datasource.postgres")
@Bean
public DataSource ds() {
return new PGSimpleDataSource();
}