开发者

What is the purpose of distancing DAO classes from ones actually being instantiated by the application

开发者 https://www.devze.com 2023-02-25 05:46 出处:网络
What is the benefit of distancing DAO classes from the ones actually being instantiated in the application code, i.e. why not just instantiate the dao class straight up in a scenario like this:

What is the benefit of distancing DAO classes from the ones actually being instantiated in the application code, i.e. why not just instantiate the dao class straight up in a scenario like this:

Class CreateIocContainer{
    p s v main(String[] args){
        new IocContainer("springMetadataFile.xml");
    }
}

Class ClassThatInstantiatesServicesViaSpringBean{
    Services services;
    // bean setter for services class
    setServices(Services services){
        this.services = services
    }
}

Class ServicesImpl implements Services
    ServicesDao servicesDao;

    String getSomethingFromDB(String argumentForQuery){
        return services开发者_JS百科Dao.getSomethingFromDB(argumentForQuery);
    }
}

Class ServicesDaoImpl implements ServicesDao{

    String getSomethingFromDb(String argumentForQuery){
        //code to return something from db
        return queryResultString;
    }
}

Also, would the class I called Class ClassThatInstantiatesServicesViaSpringBean be a factory class and usually be named Class XFactory?


Your DAOs are always interfaces they are never a class. This DAO is basically a design pattern. This separation of DAO and its implementation gives a nice technique for separating object persistence mechanism and data access logic.

Today in the bean xml file you mention,

  <bean name="ServiveDao" class="com.example.ServiceImplHibnernate">
     <property name="sessionFactory" ref="sessionFactory"/>
  </bean>

But tomorrow you may want your application to use different implementation done by you without changing the client code. For example, you have rewritten the implementation using ibatis with additional features to match up your requirement. So you write a class

   class ServiceImplIBAtis implements ServiceDao {..}

and change the xml file to load your implementation

  <bean name="ServiveDao" class="com.mycompany.ServiceImplIBAtis">
     <property name="sessionFactory" ref="sessionFactory"/>
  </bean>

Where ever the bean ServiceDao is referenced the spring will inject the ServiceImplIBAtis instance instead of ServiceImplHibnernate. Now your application does not need to know what is changed in the background. All it needs to know is there is a dao called Service and there are methods that can be used for data access.

0

精彩评论

暂无评论...
验证码 换一张
取 消