| 
 
| spring三大模块,ioc是基础,最大优点是解耦。突出两大特点,反转和依赖注入(其实就是赋值)。 
 反转的底层思想就用到工厂模式。那我们就一起揭开他的面纱。
 第一步:创建我们传统的dao层
 
 public interface TestIocDao {
 void save();
 }
 public class TestIocDaoImpl implements TestIocDao {
 @Override
 public void save() {
 System.out.println("保存到数据库");
 }
 }
 第二步:创建我们传统的service层
 
 public interface TestIocService {
 public void save();
 }
 public class TestIocServiceImpl implements TestIocService {
 
 private TestIocDao iocDao = (TestIocDao)MyBeanFactory.getBean("testIocDao");
 
 @Override
 public void save() {
 iocDao.save();
 }
 }
 第三步:创建我们的工厂
 
 public class MyBeanFactory {
 
 private static Properties properties = new Properties();
 
 static {
 InputStream inputStream = MyBeanFactory.class.getResourceAsStream("/iocBean.properties");
 try {
 properties.load(inputStream);
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 
 public static Object getBean(String name){
 String className = properties.getProperty(name);
 try {
 return Class.forName(className).newInstance();
 } catch (InstantiationException |IllegalAccessException|ClassNotFoundException e) {
 e.printStackTrace();
 }
 return null;
 }
 }
 第四步:创建模拟的xml,的txt文件
 
 testIocDao=com.pian.dao.impl.TestIocDaoImpl
 testIocService=com.pian.service.impl.TestIocServiceImpl
 第五步:创建测试用例
 
 public class TestIocFactory {
 
 private TestIocService iocService = (TestIocService)MyBeanFactory.getBean("testIocService");
 
 @Test
 public void test1(){
 iocService.save();
 }
 }
 总结:代码比较简单,就不解释了,写出来,,可以加深对spring加载机制有更清晰的了解,你也试一试吧....
 
 
 
 | 
 |