释加牟尼真身佛指舍利:Spring and Struts 2 Spring的好处,避免硬编码,处理依赖

来源:百度文库 编辑:九乡新闻网 时间:2024/04/29 13:14:56
 
如在EditAction 中存在EditService 
private EditService editService = new EditServiceInMemory();

则出现硬编码,要使用EditService,就必须NEW一个EditServiceInMemory

The above statement hard-codes a dependency between the EditActionclass and the EditServiceInMemory class. This is poor design for tworeasons.

  1. If I need to replace the EditServiceInMemory with another class that implements the EditService interface I'll have to hunt down and replace all statements where I hard-coded the dependency.
  2. I cannot test EditAction without using the EditServiceInMemory class. I cannot isolate EditAction by using a stub implementation of EditService when writing my test case because the use of EditServiceInMemory is hard-coded.

Spring provides a mechanism to manage dependencies by injecting themat run time. Struts 2 ActionSupport classes—like any other Javaclass—can be injected with a dependent object by the Spring framework.So instead of having the above code, I would have this statement inEditAction.

EditAction Class No Hard-Coded Dependency

    private EditService editService ;

At run time the Spring framework will provide an object of a class that implements the EditService interface.