如何使用Spring启动应用程序连接具有不同Ip和凭据的2个mySql数据库

时间:2017-04-01 07:07:53

标签: java mysql spring spring-mvc

我正在使用application.properties文件作为

spring.datasource.url=jdbc:mysql://IP:3306/dbname  
spring.datasource.username=name
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.dialect=org.hibernate.dialect.MYSQLDialect

1 个答案:

答案 0 :(得分:0)

######primary#############  
datasource.primary.url=jdbc:sqlserver://xx.xx.xx.xx:1433;DatabaseName=PlayNowLog  
datasource.primary.username=sa  
datasource.primary.password=xxxxxx  
datasource.primary.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver  


######secondary#############  
datasource.secondary.url=jdbc:sqlserver://xx.xx.xx.xx:1433;DatabaseName=PlayNow_New  
datasource.secondary.username=sa  
datasource.secondary.password=xxxxxx  
datasource.secondary.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver  


@Configuration  
public class GlobalDataConfiguration {  
    @Bean(name="primaryDataSource")  
    @Primary  
    @ConfigurationProperties(prefix="datasource.primary")  
    public DataSource primaryDataSource() {  
        System.out.println("-------------------- primaryDataSource init ---------------------");  
        return DataSourceBuilder.create().build();  
    }  

    @Bean(name="secondaryDataSource")  
    @ConfigurationProperties(prefix="datasource.secondary")  
    public DataSource secondaryDataSource() {  
        System.out.println("-------------------- secondaryDataSource init ---------------------");  
        return DataSourceBuilder.create().build();  
    }  
}  



@Component  
public class UserDaoImpl<T extends com.sonychina.backend.entity.statistic.SysUser> extends MyBatisBaseDao<SysUser> implements UserDao {  

    @Autowired  
    public UserDaoImpl(@Qualifier("secondaryDataSource") DataSource dataSource) {  
        super(dataSource);  
    }  
}