Normalement, pour définir une source de données avec spring-boot, définissez-la avec les propriétés, etc. comme suit, mais vous pouvez également la définir avec `` @ Bean``` comme par le passé.
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>
Si vous créez une définition @ Bean '' qui renvoie DataSource '' comme indiqué ci-dessous, elle sera utilisée. Ici, le PGSimpleDataSource '' de PostgreSQL est utilisé pour vérifier l'opération pour le moment.
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"));
        });
    }
}
En variante, il existe également une méthode de lecture des propriétés à partir d'un fichier, etc. avec `` @ 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();
    }
Recommended Posts