利用工厂模式进行代码扩展,而不用修改原来代码。在配置文件配置要生成的类,通过反射交由工厂生成对象,并将此对象交给spring管理,在项目中遇到此问题并予以解决,做一下记录。
package cn.easted.edm.core.factory.dao;
import java.util.Map;
import cn.easted.edm.core.factory.Operate;
import cn.easted.edm.core.utils.PropertiesReader;
/**
* Properties文件操作工厂类
* @author Wanghao
*
*/
public class PropertiesOperateFactory{
/**
* 根据类的名称来生产对象
* @param key key值
* @return
*/
public static Operate getOperateByClassKey(String key){
try {
Map<String, String> map = new PropertiesReader().getProperties();
Operate operate = (Operate) Class.forName(map.get(key)).newInstance();
return operate;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
package cn.easted.edm.core.utils;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* properties读取内容
*/
public class PropertiesReader {
public Map<String, String> getProperties() {
Properties props = new Properties();
Map<String, String> map = new HashMap<String, String>();
try {
InputStream in = getClass().getResourceAsStream("/type.properties");
props.load(in);
Enumeration<?> en = props.propertyNames();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String property = props.getProperty(key);
map.put(key, property);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
}
type.properties
old=cn.easted.edm.core.factory.dao.OldVersionOperateFactory
BaseAutoAware.java
package cn.easted.edm.core.utils.springInject;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
/**
* 通过反射途径获得的对象自动注入spring Bean
* @author Wanghao
*
*/
public class BaseAutoAware {
public BaseAutoAware() {
((AutowireCapableBeanFactory)retrieveBeanFactory())
.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
}
private BeanFactory retrieveBeanFactory() {
BaseLocator bl=new BaseLocator();
// BaseLocator bl = BaseLocator.getInstance();
return bl.getFactory();
}
}
BaseLocator.java
package cn.easted.edm.core.utils.springInject;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
/**
* 手动方式获取BeanFactory,实现依赖注入。
* @author Wanghao
*
*/
public