Örnek
application.properties şöyle olsunspring.datasource.primary.url=jdbc:mysql://localhost:3306/db1spring.datasource.primary.username=rootspring.datasource.primary.password=passwordspring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2spring.datasource.secondary.username=rootspring.datasource.secondary.password=password
İki DataSource tanımlarız
@Configuration public class DataSourceConfig { @Bean @Primary @ConfigurationProperties(prefix="spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix="spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } }
İki JdbcTemplateConfig tanımlarız
@Configuration public class JdbcTemplateConfig { @Bean public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource primaryDataSource) { return new JdbcTemplate(primaryDataSource); } @Bean public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) { return new JdbcTemplate(secondaryDataSource); } }
Kullanmak için şöyle yaparız
@Autowired @Qualifier("primaryJdbcTemplate") private JdbcTemplate primaryJdbcTemplate; @Autowired @Qualifier("secondaryJdbcTemplate") private JdbcTemplate secondaryJdbcTemplate; public List<User> getAllUsers() { String sql = "SELECT * FROM users"; return primaryJdbcTemplate.query(sql, new UserMapper()); } public List<Order> getAllOrders() { String sql = "SELECT * FROM orders"; return secondaryJdbcTemplate.query(sql, new OrderMapper()); }
Hiç yorum yok:
Yorum Gönder