Spring框架学习笔记(耦合性)

降低耦合度的实例

1.使用Bean工厂创造bean,降低耦合,工具类如下:

  1. 创建bean.properties。

  2. 创建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,控制反转

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值