spring中配置多数据库读取

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<context:annotation-config />
	<context:component-scan base-package="cn.springmvc" />
	<bean id="masterdataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver">
		</property>
		<property name="url" value="jdbc:mysql://localhost:3306/myoa?useUnicode=true&amp;characterEncoding=UTF-8">
		</property>
		<property name="username" value="root"></property>
		<property name="password" value="system"></property>
	</bean>
	<bean id="slavedataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver">
		</property>
		<property name="url" value="jdbc:mysql://localhost:3306/myoa2?useUnicode=true&amp;characterEncoding=UTF-8">
		</property>
		<property name="username" value="root"></property>
		<property name="password" value="system"></property>
	</bean>
	<bean id="dataSource" class="cn.springmvc.rw.DataSourceSwitch">
		<property name="targetDataSources">
			<map key-type="java.lang.String">
				<entry key="master" value-ref="masterdataSource" />
				<entry key="slave" value-ref="slavedataSource" />
			</map>
		</property>
		<property name="defaultTargetDataSource" ref="masterdataSource" />
	</bean>
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
	<bean id="manyDataSourceAspect" class="cn.springmvc.rw.DataSourceAspect" />
	<aop:config>
		<aop:aspect id="c" ref="manyDataSourceAspect">
			<aop:pointcut id="tx" expression="execution(* cn.springmvc.dao.*.*(..))" />
			<aop:before pointcut-ref="tx" method="before" />
		</aop:aspect>
	</aop:config>




	<!-- mybatis文件配置,扫描所有mapper文件  configLocation为mybatis属性 mapperLocations为所有mapper-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml" p:mapperLocations="classpath:mapper/*.xml" />

	<!-- spring与mybatis整合配置,扫描所有dao -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="cn.springmvc.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory" />

	<!-- 对数据源进行事务管理 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" 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;
 
 
/**
 * 用户表
 */
public class User {
 
    private int id;
    private int state;
    private String nickname;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getState() {
        return state;
    }
    public void setState(int state) {
        this.state = state;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
}

 

package cn.springmvc.dao;
 
import cn.springmvc.model.User;
 
 
public interface UserDAO {
 
    /**
     * 添加新用户
     * @param user
     * @return
     */
    public int insertUser(User user);
     
     
}

 

 

你可能感兴趣的:(spring)