简介
我们都知道IOC是通过工厂和反射以及容器来完成对象的创建、获取及存储的,以下代码便是简单的实现方式,通过这个demo可以更好的去理解IOC。
项目的结构如下:
- 添加bean.properties配置文件
properties文件是以key,value形式进行存储的。key值存储变量名,value存储变量类型(类路径)。
accountService=com.gzl.service.impl.AccountServiceImpl
accountDao=com.gzl.dao.impl.AccountDaoImpl
- 添加工厂类
package com.gzl.factory;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class BeanFactory {
/**
* 定义一个Properties对象
*/
private static Properties props;
/**
* 定义一个Map,用于存放我们要创建的对象。我们把它称之为容器
*/
private static Map<String, Object> beans;
//使用静态代码块为Properties对象赋值
static {
try {
//实例化对象
props = new Properties();
//获取properties文件的流对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
//实例化容器
beans = new HashMap<String, Object>();
//取出配置文件中所有的Key
Enumeration keys = props.keys();
//遍历枚举
while (keys.hasMoreElements()) {
//取出每个Key
String key = keys.nextElement().toString();
//根据key获取value
String beanPath = props.getProperty(key);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key和value存入容器中
beans.put(key, value);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
/**
* 根据bean的名称获取对象
*
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
return beans.get(beanName);
}
}
- 首先添加dao层接口
package com.gzl.dao;
/**
* 账户的持久层接口
*/
public interface IAccountDao {
void saveAccount();
}
- 添加dao层接口对应的实现类
package com.gzl.dao.impl;
import com.gzl.dao.IAccountDao;
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements IAccountDao {
public void saveAccount() {
System.out.println("保存了账户");
}
}
- 添加service层接口
package com.gzl.service;
/**
* 账户业务层的接口
*/
public interface IAccountService {
/**
* 模拟保存账户
*/
void saveAccount();
}
- 添加service层实现类
package com.gzl.service.impl;
import com.gzl.dao.IAccountDao;
import com.gzl.factory.BeanFactory;
import com.gzl.service.IAccountService;
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");
public void saveAccount() {
int i = 1;
accountDao.saveAccount();
System.out.println(i);
i++;
}
}
- 添加一个类,然后添加主函数进行测试
package com.gzl;
import com.gzl.factory.BeanFactory;
import com.gzl.service.IAccountService;
/**
* 模拟一个表现层,用于调用业务层
*/
public class Client {
public static void main(String[] args) {
//IAccountService as = new AccountServiceImpl();
for (int i = 0; i < 5; i++) {
IAccountService as = (IAccountService) BeanFactory.getBean("accountService");
System.out.println(as);
as.saveAccount();
}
}
}
- 运行结果
总结
以上观察结果多次调用一直是一个对象,spring也是如此,他可以在对象创建前设置该对象是单例还是多例,默认是单例,所谓的单例就是容器当中始终存储的只有一个对象的实例,多次使用的情况下都是使用的这一个对象实例!
真实的IOC要比这个复杂的多,还要考虑对象的单例以及多例、以及线程安全等各种问题,这个demo只能大概了解IOC的思路。