手动实现spring的ioc注入

手动实现spring的ioc注入

需要配置文件,实现一个工厂从配置文件中读取,实现自动new对象的操作
## bean.properties配置文件内容
accountService=com.zho.service.impl.IAccountServiceImpl
accountDao=com.zho.dao1.impl.IAccountDaoImpl

创建一个工厂代替spring实现ioc

package com.zho.factory;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class BeanFactory{
	private static Properties props;//读取配置文件
	private static Map<String, Object> beans;//创建对象存入map中,需要使用时从这里取
	
	//静态块初始化对象
	static{
		try{
			props = new Properties();
			//找到项目的资源路径
			InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("Bean.properties");
			props.load(in);
			beans = new HashMap<>();
			//获取键值
			Enumeration keys = props.keys();
			
			while(keys.hasMoreElements()){
				String key = keys.nextElement().toString();
				//获取包名及类名
				String beanPath = props.getProperty(key);
				//利用反射创建实例对象
				Object value = Class.forName(beanPath).getDeclaredConstructor().newInstance();
				//创建完对象存入map中
				beans.put(key, value);
			}
			
		} catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("初始化失败");
		}
	}


	//创建一个静态方法获取实例
	public static Object getBean(String beanName) {
		return beans.get(beanName);
	}

}

service层代码

package com.zho.service.impl;

import com.zho.dao1.IAccountDao;
import com.zho.factory.BeanFactory;
import com.zho.service.IAccountService;

public class IAccountServiceImpl implements IAccountService {

    //    private IAccountDao accountDao = new IAccountDaoImpl();
    //从工厂中生产dao对象
    private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");
    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }
}

web层

package com.zho.ui;

import com.zho.factory.BeanFactory;
import com.zho.service.IAccountService;

public class Client {
    public static void main(String[] args) {

//        IAccountService as = new IAccountServiceImpl();
        for (int i = 0; i < 5; i++) {
        //从中工厂生产service对象
        //由于工厂中生产的过程中,是存储在一个map中的,所以从工厂中获多个serive对象的地址位同一地址
            IAccountService as = (IAccountService) BeanFactory.getBean("accountService");
            System.out.println(as);
        }
//        as.saveAccount();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值