我现在的思路是在我的application中配置两个数据库
利用aop自动切换数据库
<bean id="dataSource" class="com.staples.*.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="dataSourceOne" value-ref=" dataSourceOne " />
<entry key="dataSourceTwo" value-ref=" dataSourceTwo " />
</map>
</property>
<property name="defaultTargetDataSource" ref=" dataSourceOne " />
</bean>
<bean id="dataSourceInterceptor" class="com.staples.*. DataSourceInterceptor " />
<aop:config>
<aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor">
<aop:pointcut id="dsOracleOne " expression="execution(* com.controller.生产数据的controller.*.*(..))" />
<aop:pointcut id="dsOracleTwo" expression="execution(*com.service.日志的service.*.*(..))" />
<aop:before method="setdataSourceOne" pointcut-ref="dsOracleOne"/>
<aop:before method="setdataSourceTwo" pointcut-ref=" dsOracleTwo "/>
</aop:aspect>
</aop:config>
下面是我的数据库切换方法
DynamicDataSource.Java
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DatabaseContextHolder.getCustomerType();
}
}
DataSourceInterceptor.java
import org.aspectj.lang.JoinPoint;
public class DataSourceInterceptor {
public void setdataSourceMysql(JoinPoint jp) {
DatabaseContextHolder.setCustomerType("dataSourceOne");
}
public void setdataSourceOracle(JoinPoint jp) {
DatabaseContextHolder.setCustomerType("dataSourceTwo");
}
}
DatabaseContextHolder.java
public class DatabaseContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setCustomerType(String customerType) {
contextHolder.set(customerType);
}
public static String getCustomerType() {
return contextHolder.get();
}
public static void clearCustomerType() {
contextHolder.remove();
}
}
请问我可不可以这样写我的aop啊
我是为了实现日志和生产的数据源分离,而我在保存日志的时候都是直接在事务层调我日志的service,这样可以实现吗