spring自定义bean工厂模式解耦
2024-10-20 16:10:18
在resources下创建bean.properties
accountService=cn.flypig666.service.impl.AccountServiceImpl
accountDao=cn.flypig666.dao.impl.AccountDaoImpl
创建工厂:BeanFactory.java
创建单例对象效果更好
创建Map<String,Object>类型的容器beans
//定义一个Properties对象
private static Properties props; //定义一个Map,用于存放我们要创建的对象,称之为容器
private static Map<String,Object> beans; //使用静态代码块为Properties对象赋值
static {
try {
//实例化对象
props = new Properties();
//获取properties文件的流对象,创建在resources文件夹下的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失败");
}
} public static Object getBean(String beanName){
return beans.get(beanName);
}
/**
* 根据Bean的名称获取bean对象
* @param beanName
* @return
*/
public static Object getBean(String beanName){
Object bean = null;
try{
String beanPath = props.getProperty(beanName);
System.out.println(beanPath);
bean = Class.forName(beanPath).newInstance();
}catch (Exception e){
e.printStackTrace();
}
return bean;
} }
通过反射获取对象
/**
* 账户业务层实现类
*/
public class AccountServiceImpl implements IAccountService { //private IAccountDao accountDao = new AccountDaoImpl();
private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao"); public void saveAccount(){
accountDao.saveAccount();
}
}
/**
* 模拟一个表现层,用于调用业务层
*/
public class Client { public static void main(String[] args) {
// IAccountService accountService = new AccountServiceImpl();
IAccountService accountService = (IAccountService) BeanFactory.getBean("accountService");
accountService.saveAccount();
}
}
最新文章
- HTML 学习笔记 CSS3 (多列)
- ruby api 2.1新增改变
- CSS3之创建透明边框三角
- Jtemplates 基本语法
- webx学习笔记
- 玩转Android之在线视频播放控件Vitamio的使用
- C#利用NPOI生成具有精确列宽行高的Excel文件
- ubuntu远程连接
- python可变参数调用函数的问题
- ios UIKit动力 分类: ios技术 2015-07-14 12:55 196人阅读 评论(0) 收藏
- go 语言的序列化与反序列化
- 利用toggle实现背包
- Django开发目录
- 如何使用Shell判断版本号的大小
- vue为app做h5页面,如何做到同域名对应不同版本的h5代码
- C语言中的地址传递(传指针,传递给形参的指针仍然是实参指针的一份拷贝)
- Android源码阅读笔记二 消息处理机制
- git openssl 模块生成 https 请求的 ssl 测试证书
- pring Boot 与Spring Cloud版本对应
- LeetCode 35 Search Insert Position(查找插入位置)