1、创建一个 bean.properties 配置文件(key-value)
AccountService=ouhe.AccountServiceImpl
AccountDao=ouhe.AccountDaoImpl
2、创建工厂类
package ouhe;
import java.util.ResourceBundle;
//创建Bean对象的工厂
public class BeanFactory {
/*
* 只能用于读取properties文件
* 只能读取,不能写入
* 只能读取类路径下的文件
* */
private static ResourceBundle rb = ResourceBundle.getBundle("bean");
//用于创建Bean对象的方法
public static Object getBean(String beanName) throws ClassNotFoundException {
String s = rb.getString(beanName);
Object clazz = null;
try {
clazz = Class.forName(s).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
return clazz;
}
}
3、创建表现层,业务逻辑层、持久层的类
package ouhe;
//表现层
public class Client {
public static void main(String[] args) throws ClassNotFoundException {
//IAccountService as = new AccountServiceImpl();
IAccountService as = (IAccountService) BeanFactory.getBean("AccountService");
as.save();
}
}
package ouhe;
//业务层实现类
public class AccountServiceImpl implements IAccountService{
@Override
public void save() throws ClassNotFoundException {
//IAccountDao ad = new AccountDaoImpl();
IAccountDao ad = (IAccountDao) BeanFactory.getBean("AccountDao");
ad.save();
}
}