标签:pat bean factory cli more 失败 void name vat
在resources下创建bean.properties
accountService=cn.flypig666.service.impl.AccountServiceImpl
accountDao=cn.flypig666.dao.impl.AccountDaoImpl
创建工厂:BeanFactory.java
创建单例对象效果更好
创建Map<String,Object>类型的容器beans
1 //定义一个Properties对象 2 private static Properties props; 3 4 //定义一个Map,用于存放我们要创建的对象,称之为容器 5 private static Map<String,Object> beans; 6 7 //使用静态代码块为Properties对象赋值 8 static { 9 try { 10 //实例化对象 11 props = new Properties(); 12 //获取properties文件的流对象,创建在resources文件夹下的properties文件会成为类根路径下的文件,不用写包名 13 InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"); 14 props.load(in); 15 //实例化容器 16 beans = new HashMap<String, Object>(); 17 //取出配置文件中所有的 Key 18 Enumeration keys = props.keys(); 19 //遍历枚举 20 while (keys.hasMoreElements()){ 21 //取出每个key 22 String key = keys.nextElement().toString(); 23 //根据key获取value 24 String beanPath = props.getProperty(key); 25 //反射创建对象 26 Object value = Class.forName(beanPath).newInstance(); 27 //把key和value存入容器中 28 beans.put(key,value); 29 } 30 } catch (Exception e) { 31 throw new ExceptionInInitializerError("初始化properties失败"); 32 } 33 } 34 35 public static Object getBean(String beanName){ 36 return beans.get(beanName); 37 }
1 /** 2 * 根据Bean的名称获取bean对象 3 * @param beanName 4 * @return 5 */ 6 public static Object getBean(String beanName){ 7 Object bean = null; 8 try{ 9 String beanPath = props.getProperty(beanName); 10 System.out.println(beanPath); 11 bean = Class.forName(beanPath).newInstance(); 12 }catch (Exception e){ 13 e.printStackTrace(); 14 } 15 return bean; 16 } 17 18 }
通过反射获取对象
/** * 账户业务层实现类 */ 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(); } }
标签:pat bean factory cli more 失败 void name vat
原文地址:https://www.cnblogs.com/flypig666/p/11510970.html