Normally, to define a data source with spring-boot, set it with properties etc. as follows, but you can also define it with `` `@ Bean``` as in the past.
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>
If you create a `@ Bean``` definition that returns ``` `DataSource``` as shown below, it will be used. Here, PostgreSQL's
`PGSimpleDataSource``` is used to check the operation for the time being.
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"));
});
}
}
As a variation, there is also a method of reading properties from a file etc. with @ 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