Nim*_*sky 6 java spring unit-testing dependency-injection
我使用的是Spring,这里是一个控制器:
@Controller
public class PersonController {
@Resource(name="PersonService")
private PersonService personService;
@RequestMapping(value = "/Person", method = RequestMethod.GET)
public String getPersons(Model model) {
// Retrieve all persons by delegating the call to PersonService
List<Person> persons = personService.getAll();
// Attach persons to the Model
model.addAttribute("persons", persons);
//then return to view jsp
}
Run Code Online (Sandbox Code Playgroud)
这是一项服务:
@Service("personService")
@Transactional
public class PersonService {
public List<Person> getAll() {
//do whatever
}
}
Run Code Online (Sandbox Code Playgroud)
但是,要正确使用DI,我应该更改控制器以使用接口(?),如下所示:
@Controller
public class PersonController {
@Resource(name="personService")
private IPersonService personService; //Now an interface
}
Run Code Online (Sandbox Code Playgroud)
例如,这将允许我使用两个服务,一个测试,一个实时.我可以通过添加/删除服务上的注释来改变:
@Service("personService") // this line would be added/removed
@Transactional
public class LivePersonService implements IPersonService {
public List<Person> getAll() {
//do whatever
}
}
Run Code Online (Sandbox Code Playgroud)
和
@Service("personService") //this line would be added/removed
@Transactional
public class TestPersonService implements IPersonService {
public List<Person> getAll() {
//do something else
}
}
Run Code Online (Sandbox Code Playgroud)
然而,由于代码必须重新编译,所以失去了一个主要好处?如果我使用xml查找,我可以动态改变依赖?
| 归档时间: |
|
| 查看次数: |
461 次 |
| 最近记录: |