数据库的配置文件 DynamicDataSource.properties
User=root
Password=root
test.Url=jdbc:mysql://localhost:3306/test
Driver=com.mysql.jdbc.Driver
hotel.Url=jdbc:mysql://localhost:3306/hotel
继承自AbstractRouteDataSource 的DynamicDataSource
package com.wsc.DBMySQL;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
/**
* @Author: wsc
* @Date: 2019/7/17 0:13
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return CustomerContextHolder.getCustomerType();
}
}
数据共享的 CustomerContextHolder.java
package com.wsc.DBMySQL;
public class CustomerContextHolder {
public static final String DATA_SOURCE_A = "test";
public static final String DATA_SOURCE_B = "hotel ";
private static final ThreadLocal contextHolder = new ThreadLocal();
public static void setCustomerType(String customerType) {
contextHolder.set(customerType);
}
public static String getCustomerType() {
return contextHolder.get();
}
public static void clearCustomerType() {
contextHolder.remove();
}
}
自定义的接口
package com.wsc.AOP;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
/**
*
* @author dell
*
*/
public @interface CommDB {
String value() default "test";
}
对自定义的接口添加Aop进行方法增强
package com.wsc.AOP;
import javax.annotation.Resource;
import com.wsc.DBMySQL.CustomerContextHolder;
import com.wsc.DBMySQL.DynamicDataSource;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class CommDB_AOP {
@Pointcut("@annotation(com.wsc.AOP.CommDB)")
public void pointCut() {};
@Before(value="pointCut() && @annotation(db)",argNames ="db")
public void before(JoinPoint joinPoint,CommDB db) {
String dbName = db.value();
CustomerContextHolder.setCustomerType(dbName);
}
}
执行的SQL测试语句
package com.wsc.DBMySQL;
import com.wsc.AOP.CommDB;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/**
* @author wsc
*/
@Service
public class SQL_execute {
@Autowired
private JdbcTemplate jdbcTemplate;
@CommDB
public void insertData(){
String sql = "insert into img set belong=?,src=?";
jdbcTemplate.update(sql,new Object[] {"wsc","c:/img"});
}
@CommDB("test")
public void insertData2(){
String sql = "insert into img set belong=?,src=?";
jdbcTemplate.update(sql,new Object[] {"wsc","c:/img"});
}
@CommDB("hotel")
public void insertData3(){
String sql = "insert into img set belong=?,src=?";
jdbcTemplate.update(sql,new Object[] {"wsc","c:/img"});
}
}
最关键的Bean.xml文件来了,我个人推荐使用IDEA编写Bean文件,因为我使用eclipse是DynamicDataSource的setTargetDataSources写错了eclipse尽然没报错也没变色,后来换成IDEA才找出这个错误,而且还有提示
执行测试文件,当然,我写在这里都是测试 通过的例子,你们可以参考参考
import com.wsc.DBMySQL.SQL_execute;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Author: wsc
* @Date: 2019/7/17 0:30
*/
public class BeanXMLTest {
@Test
public void test1(){
ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("Bean.xml");
SQL_execute sql =(SQL_execute)context.getBean(SQL_execute.class);
sql.insertData();
}
}
直接上代码,这里需要说明一下,由于方法是没有
package com.wsc.SQLConfig;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringValueResolver;
import com.alibaba.druid.pool.DruidDataSource;
@ComponentScan("com.wsc")
@Configuration
@EnableAspectJAutoProxy
public class SQLConfig{
@Bean(initMethod="init",destroyMethod="close")
public DruidDataSource dataSourceTest() throws SQLException{
DruidDataSource datasource = new DruidDataSource();
datasource.setInitialSize(2);
datasource.setMaxActive(10);
datasource.setMaxIdle(5);
datasource.setMaxWait(30000);
datasource.setValidationQuery("SELECT 1");
datasource.setTestOnBorrow(false);
datasource.setTestOnReturn(false);
datasource.setTestWhileIdle(true);
datasource.setTimeBetweenEvictionRunsMillis(60000);
datasource.setMinEvictableIdleTimeMillis(25200000);
datasource.setRemoveAbandoned(true);
datasource.setRemoveAbandonedTimeout(1800);
datasource.setLogAbandoned(true);
datasource.setFilters("mergeStat");
datasource.setUrl("jdbc:mysql://localhost:3306/test");
datasource.setUsername("root");
datasource.setPassword("root");
datasource.setDriverClassName("com.mysql.jdbc.Driver");
datasource.setMaxActive(15);
return datasource;
}
@Bean(initMethod="init",destroyMethod="close")
public DruidDataSource dataSourceHotel() throws SQLException {
DruidDataSource datasource = new DruidDataSource();
datasource.setInitialSize(2);
datasource.setMaxActive(10);
datasource.setMaxIdle(5);
datasource.setMaxWait(30000);
datasource.setValidationQuery("SELECT 1");
datasource.setTestOnBorrow(false);
datasource.setTestOnReturn(false);
datasource.setTestWhileIdle(true);
datasource.setTimeBetweenEvictionRunsMillis(60000);
datasource.setMinEvictableIdleTimeMillis(25200000);
datasource.setRemoveAbandoned(true);
datasource.setRemoveAbandonedTimeout(1800);
datasource.setLogAbandoned(true);
datasource.setFilters("mergeStat");
datasource.setUrl("jdbc:mysql://localhost:3306/hotel");
datasource.setUsername("root");
datasource.setPassword("root");
datasource.setDriverClassName("com.mysql.jdbc.Driver");
datasource.setMaxActive(15);
return datasource;
}
@Bean
public DynamicDataSource dynamicDataSource() throws SQLException {
DynamicDataSource data = new DynamicDataSource();
DruidDataSource dataSourceTest = dataSourceTest();
DruidDataSource dataSourceHotel = dataSourceHotel();
System.out.println("test:\t"+dataSourceTest.getUrl());
System.out.println("hotel:\t"+dataSourceHotel.getUrl());
Map map = new HashMap();
map.put("test", dataSourceTest);
map.put("hotel", dataSourceHotel);
data.setTargetDataSources(map);
data.setDefaultTargetDataSource(dataSourceTest());
return data;
}
@Bean
public JdbcTemplate jdbcTemplate() throws SQLException {
JdbcTemplate tem = new JdbcTemplate();
tem.setDataSource(dynamicDataSource());
return tem;
}
}
测试用例:
import com.wsc.DBMySQL.SQL_execute;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Author: wsc
* @Date: 2019/7/17 0:30
*/
public class BeanXMLTest {
@Test
public void test1(){
ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("Bean.xml");
SQL_execute sql =(SQL_execute)context.getBean(SQL_execute.class);
sql.insertData();
}
}
如果喜欢的我的内容,就关注我一波吧!
学习啊,学习啊,学习也是一种挣扎.