//一般需要两个条件: 1、设置配置文件bean.properties
// 2、使用反射机制,获取代理对象的实现类
//配置文件bean.properties(注意不要加“;”号)
accountDao=com.hope.dao.impl.AccountDaoImplaccountService=com.hope.service.impl.AccountServiceImpl
package com.hope.factory;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/** * @author newcityman * @date 2019/11/18 - 14:44 * 第一个:需要一个配置文件来配置我们的service和dao * 第二个:通过读取配置文件中配置的内容,反射创建对象 */public class BeanFactory { //定义一个properties对象 public static Properties props; static { try { //定义一个properties对象 props = new Properties(); //获取properties文件的流对象 InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"); props.load(in); } catch (IOException e) { throw new ExceptionInInitializerError("初始化propteies失败"); } } /** * 根据bean的名称获取bean对象 * * @param beanName * @return */ public static Object getBean(String beanName) { Object bean=null; try { String beanPath = props.getProperty(beanName); bean = Class.forName(beanPath).newInstance(); } catch (Exception e) { e.printStackTrace(); } return bean; }}
package com.hope.ui;import com.hope.factory.BeanFactory;import com.hope.service.IAccountService;/** * @author newcityman * @date 2019/11/18 - 14:23 */public class Client { public static void main(String[] args) {// IAccountService accountService= new accountServiceImpl(); IAccountService accountService=(IAccountService)BeanFactory.getBean("accountService"); accountService.findAll(); }}