Giriş
Şu satırı dahil ederiz
Şu satırı dahil ederiz
import org.springframework.boot.jdbc.DataSourceBuilder;
Açıklaması şöyle
DataSourceBuilder is a utility or convenience class in spring boot that provides a convenient way to create and configure a datasource.Using this class, we can create a datasource in using connection parameters, such as database URL, username, and password.
Örnek
Şöyle yaparız
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
return DataSourceBuilder
.create()
.url("jdbc:mysql://localhost/appdb")
.username("user")
.password("password")
.driverClassName("com.mysql.jdbc.Driver")
.build();
}
}
Açıklaması şöyle
Note that we are marking the class with @Configuration annotation, which marks it as source of beans.And in the configuration class, we expose a bean of type DataSource.
Örnek
Şöyle yaparız.
Diğer
Bu sınıfı yaratmak için DataSourceProperties kullanılabilir.
Örnek
Şöyle yaparız.
Şöyle yaparız.
@Bean(name = "dataSource")
public DataSource getDataSource() {
DataSource dataSource = DataSourceBuilder
.create()
.username("ALERTTEST")
.password("ALERTTEST")
.url("jdbc:oracle:thin:@192.168.0.198:1521:FCUBS")
.driverClassName("oracle.jdbc.OracleDriver")
.build();
return dataSource;
}
Diğer
Bu sınıfı yaratmak için DataSourceProperties kullanılabilir.
Örnek
Şöyle yaparız.
# first db
spring.datasource.url = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
spring.datasource.driverClassName = oracle.jdbc.OracleDriver
# second db ...
spring.secondDatasource.url = [url]
spring.secondDatasource.username = [username]
spring.secondDatasource.password = [password]
spring.secondDatasource.driverClassName = oracle.jdbc.OracleDriver
@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix="spring.secondDatasource")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
ÖrnekŞöyle yaparız.
@Configuration
@EnableTransactionManagement
public class JdbcDatasource {
@Bean
@ConfigurationProperties(prefix = "my.datasource")
public DataSource myDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public JdbcTemplate myJdbcTemplate() {
return new JdbcTemplate(myDataSource());
}
@Bean
public PlatformTransactionManager myTransactionManager() {
return new DataSourceTransactionManager(myDataSource());
}
...
}
Hiç yorum yok:
Yorum Gönder