LoginSignup
0
0

More than 5 years have passed since last update.

spring-bootでデータソースをプロパティでなくコードで定義

Posted at

通常、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();
    }

参考URL

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0