Spring学习:程序的耦合和解耦的思路分析

程序的耦合java

  耦合:程序间的依赖关系spa

    包括:code

      类之间的依赖xml

      方法间的依赖对象

  解耦:blog

    下降程序间的依赖关系开发

  在实际开发中:get

    应该作到,编译期不依赖,运行时才依赖it

  解耦思路:io

    第一步:使用反射来建立对象,而避免使用new关键词

    第二步:经过读取配置文件来获取要建立的对象全限定类名


建立BeanFactory  

 1 /**
 2  * 一个建立Bean对象的工厂  3  *  4  * Bean:在计算机英语中,有可重用组件的含义  5  * JavaBean:用java语言编写的可重用组件  6  * javabean > 实体类  7  *  8  * 它就是建立咱们的service的dao对象的  9  * 第一个:须要一个配置文件来配置咱们的service和dao 10  * 配置的内容:惟一标识=全限定类名 11  * 第二个:经过读取配置文件中配置的内容,反射建立对象 12  * 13  * 配置文件能够是xml也能够是properties 14  * 15  */
16 public class BeanFactory { 17 
18     //定义一个Properties对象
19     private static Properties props; 20 
21     //使用静态代码块为Properties对象赋值
22     static { 23         try { 24             //实例化对象
25             props = new Properties(); 26             //获取properties文件的流对象,建立在resources文件夹下的properties文件会成为类根路径下的文件,不用写包名
27             InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"); 28  props.load(in); 29         } catch (Exception e) { 30             throw new ExceptionInInitializerError("初始化properties失败"); 31  } 32  } 33 
34     /**
35  * 根据Bean的名称获取bean对象 36  * @param beanName 37  * @return
38      */
39     public static Object getBean(String beanName){ 40         Object bean = null; 41         try{ 42             String beanPath = props.getProperty(beanName); 43  System.out.println(beanPath); 44             bean = Class.forName(beanPath).newInstance(); 45         }catch (Exception e){ 46  e.printStackTrace(); 47  } 48         return bean; 49  } 50 
51 }

调用BeanFactory,反射建立对象

 1 /**
 2  * 帐户业务层实现类  3  */
 4 public class AccountServiceImpl implements IAccountService {  5 
 6     //private IAccountDao accountDao = new AccountDaoImpl();
 7     private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");  8 
 9     public void saveAccount(){ 10  accountDao.saveAccount(); 11  } 12 }
 1 /**
 2  * 模拟一个表现层,用于调用业务层  3  */
 4 public class Client {  5 
 6     public static void main(String[] args) {  7 // IAccountService accountService = new AccountServiceImpl();
 8         IAccountService accountService = (IAccountService) BeanFactory.getBean("accountService");  9  accountService.saveAccount(); 10  } 11 }
相关文章
相关标签/搜索