Spring框架学习笔记(耦合性)
降低耦合度的实例
1.使用Bean工厂创造bean,降低耦合,工具类如下:
- 创建bean.properties。
- 创建Bean Factory类,使用静态代码块加载生产储存beanPath的Map集合
public class BeanFactory(){
//创建properity实例
private static Properties props;
//定义一个Map用于存放生成的bean对象
private static Map<String,Object>;
//使用静态代码块加载properity
static{
try{
//实例化props
props = new properites;
//加载配置文件
InputStream in = BeanFactory.class.getClassLorder.getResourceAsStream(bean.properties);
props.(in);
//创建实例化一个容器
beans = new HashMap<String,Object>;
//取出配置文件的key
Enumeration keys = props.keys();
//遍历枚举
while(keys.hasMoreElements()){
String key = keys.nextElement().toString()
//取出beanPath
String beanPath = props.getProperties(key)
//反射创建对象
Object value = Clsss.forName(beanPath).newInstance
//把key和value存储到Map中
beans.put(key,value)
}
}catch(Exception e){
throw new ExceptionInInitializerError("初始化properties失败")
}
}
public static Object getBean(String BeanName){
//根据bean的名称获取对象
return beans.get(beanName);
}
两种调用方法
//1.通过类实现接口创建对象 private ImuserDao userDao = new UserDaoImp(); //2.交给工厂处理、类之间的联系降低 private ImuserDao userDao = BeanFctory.getBean(beanName:userDao)
2.把创造对象的功能交给工厂或者框架,降低程序间的耦合性为IOC,控制反转
