我正在使用 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
}
这是一项服务:
@Service("personService")
@Transactional
public class PersonService {
public List<Person> getAll() {
//do whatever
}
}
但是,为了正确使用 DI,我应该更改控制器以使用接口(?),如下所示:
@Controller
public class PersonController {
@Resource(name="personService")
private IPersonService personService; //Now an interface
}
例如,这将允许我使用两项服务,一项是测试,一项是实时服务。我可以通过添加/删除服务上的注释来更改:
@Service("personService") // this line would be added/removed
@Transactional
public class LivePersonService implements IPersonService {
public List<Person> getAll() {
//do whatever
}
}
and
@Service("personService") //this line would be added/removed
@Transactional
public class TestPersonService implements IPersonService {
public List<Person> getAll() {
//do something else
}
}
然而,由于代码必须重新编译,主要好处之一就丧失了?然而,如果我使用 xml 查找,我可以即时更改依赖项吗?