有的时候项目中可能要从另外一个系统取数据 如果另外一个系统能提供接口就很好解决 如果没有接口 便可以配置多个数据源切换访问
<1>:这是数据源和事务扫描注入的配置 访问多个数据源只需要建立多个数据源和事务这一套配置文件
这是第一个数据源
<2>这是第二个数据源 和第一个数据源一样 需要有事务 扫描注解
不同的是数据源的 url username 和password 用的是第二个数据源的连接 用户名和密码
<3>这个时候就可以用两个数据源进行切换注入 从而使用不同数据源的service
这是service里面的方法 该怎么写就是怎么写 该怎么注解就怎么注解 不用做特殊的步骤
-
@Service("partyService")
-
public class PartyServiceImpl implements PartyService {
-
-
@Autowired
-
private PartyDao partyDao;
-
-
@Override
-
public List<Emp> getAllEmp() throws SQLException {
-
return partyDao.getAllEmp();
-
}
-
-
}
Dao层也是一样 该怎么写就怎么写 该怎么注解就怎么注解
然后可以写一个测试类试一下连接
-
@RunWith(SpringJUnit4ClassRunner.class)
-
@ContextConfiguration(locations = { "classpath:spring.xml" })
-
public class DataSourceTest extends AbstractTransactionalJUnit4SpringContextTests {
-
-
-
-
-
-
-
-
-
-
-
-
-
@Test
-
@Rollback(true)
-
public void testGetAllEmp() throws SQLException {
-
ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:config/hymanager/hymanager_spring.xml");
-
PartyService partyService = (PartyService) ac.getBean("partyService");
-
List<Emp> list = partyService.getAllEmp();
-
for (Emp emp : list) {
-
System.out.println(emp.getEmpno());
-
}
-
}
这样就可以封装一个父类
-
public class DataSourceChange {
-
-
public ApplicationContext otherDataSource=new FileSystemXmlApplicationContext("classpath:config/hymanager/hymanager_spring.xml");
-
-
public ApplicationContext defaultDataSource=new FileSystemXmlApplicationContext("classpath:config/spring_commons.xml");
-
-
-
-
-
-
-
-
-
-
-
-
-
-
public Object now(String beanName) {
-
return defaultDataSource.getBean(beanName);
-
}
-
public Object after(String beanName) {
-
return otherDataSource.getBean(beanName);
-
}
-
}
要使用多个数据源的类就可以继承这个父类
-
public class HyMangerEmpDataHandle extends DataSourceChange {
-
-
private PartyService partyService=(PartyService) after("partyService");
-
-
更换配置切换第一套数据源获取注入empService
-
private EmpService empService=(EmpService) now("empService");
-
-
private static Logger log=LoggerFactory.getLogger(PartyService.class);
-
-
-
-
-
-
-
-
-
-
-
-
-
public void leadingAllEmp() throws SQLException {
-
List<Emp> partyList=partyService.getAllEmp();
-
for(Emp emp:partyList) {
-
empService.addEmp(emp);
-
}
-
}
-
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/9399028/viewspace-2106641/
,如需转载,请注明出处,否则将追究法律责任。