通常情况下,我们会把项目中的进行持久化操作的各个Dao实例交由spring IOC容器进行管理。利用依赖注入使用该Dao实例。
那么不妨可以尝试这样做,定义一个存放所有Dao实例的工厂,将项目中所有的Dao实例都转化为该工厂的静态成员,那当我们需要使用的时候,就可以很灵活的去调用各个持久化的方法。
实例(以mybaits为例)
1、假定目前工程的Dao模块存在3个mapper接口:
AxxMapper
BxxMapper
CxxMapper
2、定义MapperFactory
的基类BaseMapperFactory
。利用反射的机制,将非静态成员的值赋予静态成员变量。
public class BaseMapperFactory {
private static final Logger logger = LoggerFactory.getLogger(MapperFactory.class);
/**
*
* 初始化方法主要用于给static member 赋值,
* 因为静态成员是无法使用依赖注入的,
* 所以需要借助与其相同类型的非静态成员执行赋值操作。
*
* 内部成员变量命名方式:
* @Autowired
* private AxxMapper _axxMapper ;
* private static AxxMapper axxMapper;
*/
public void init(){
try {
Field[] fields = this.getClass().getDeclaredFields() ;
for(int i = 0 ; i < fields.length ; i ++){
Field field = fields[i] ;
String fieldName = field.getName() ;
if(fieldName.startsWith("_")){
String staticFieldName = fieldName.substring(1) ;
Field staticField = this.getClass().getDeclaredField(staticFieldName) ;
field.setAccessible(true);
staticField.set(this , field.get(this)) ;
staticField.setAccessible(true) ;
}
}
}catch (Exception e){
logger.error("赋值过程出现Exception --->",e);
}
}
}
3、定义MapperFactory
工厂类
public class MapperFactory extends BaseMapperFactory {
@Autowired("axxMapper")
private AxxMapper _axxMapper;
private static AxxMapper axxMapper;
@Autowired("bxxMapper")
private BxxMapper _bxxMapper;
private static BxxMapper bxxMapper;
@Autowired("cxxMapper")
private CxxMapper _cxxMapper;
private static CxxMapper cxxMapper;
/**
* 依赖注入后,执行父类的init();
*
* 构造方法 >> 依赖注入 >> init()
*/
@Override
@PostConstruct
public void init() {
super.init();
}
}
4、至此,调用就变的非常简单、优雅了:
MapperFactory.axxMapper.save(object)
MapperFactory.bxxMapper.update(object)
MapperFactory.cxxMapper.delete(object)
...