spring中装备多数据库读取ITeye - 乐橙lc8

spring中装备多数据库读取ITeye

2019-01-13 14:13:04 | 作者: 沛凝 | 标签: 装备,一切,文件 | 浏览: 1681

!-- mybatis文件装备,扫描一切mapper文件 configLocation为mybatis特点 mapperLocations为一切mapper-- bean id="sqlSessionFactory" p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml" p:mapperLocations="classpath:mapper/*.xml" / !-- spring与mybatis整合装备,扫描一切dao -- bean p:basePackage="cn.springmvc.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory" / !-- 对数据源进行事务管理 -- bean id="transactionManager" p:dataSource-ref="dataSource" / /beans

 

package cn.springmvc.rw;
public class DataSourceUtil {
 public static final ThreadLocal String holder = new ThreadLocal String 
 public static void putDataSource(String name) {
 holder.set(name);
 public static String getDataSouce() {
 return holder.get();

 

package cn.springmvc.rw;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DataSourceSwitch extends AbstractRoutingDataSource {
 @Override
 protected Object determineCurrentLookupKey() {
 System.out.println("============"+DataSourceUtil.getDataSouce());
 return DataSourceUtil.getDataSouce();

 

package cn.springmvc.rw;
import org.aspectj.lang.JoinPoint;
public class DataSourceAspect {
 public void before(JoinPoint point) {
 String method = point.getSignature().getName();
 System.out.println("阻拦的办法名为"+method);
 if (method.startsWith("save")||method.startsWith("update")||method.startsWith("delete")) {
 DataSourceUtil.putDataSource("master");
 }else{
 DataSourceUtil.putDataSource("slave");
}

 

package cn.springmvc.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.springmvc.model.User;
import cn.springmvc.service.UserService;
public class UserTest {
 private UserService userService;
 @Before
 public void before() {
 @SuppressWarnings("resource")
 ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "classpath:conf/applicationContext.xml", "classpath:mybatis-config.xml" });
 userService = (UserService) context.getBean("userService");
 @Test
 public void addUser() {
 User user = new User();
 user.setNickname("你好");
 user.setState(2);
 System.out.println(userService.insertUser(user));
}

 

package cn.springmvc.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.springmvc.dao.UserDAO;
import cn.springmvc.model.User;
@Service
public class UserService {
 @Autowired
 private UserDAO userDAO;
 public int insertUser(User user) {
 return userDAO.insertUser(user);
}

 

package cn.springmvc.model;                          
			
版权声明
本文来源于网络,版权归原作者所有,其内容与观点不代表乐橙lc8立场。转载文章仅为传播更有价值的信息,如采编人员采编有误或者版权原因,请与我们联系,我们核实后立即修改或删除。

猜您喜欢的文章