使用注释注入依赖项是否会消除依赖注入(外部配置)的主要好处?

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查找,我可以动态改变依赖?

Mr.*_*art 4

配置仍然是外部的,因为它位于您定义要注入哪个实现的外部。在类内部,您只需对类所依赖的东西“名称”进行硬编码(这是可以的,因为这种依赖关系是类所固有的)。

也就是说,您可以使用 XML 覆盖测试执行代码的注释(您的测试将有一个特定的 XML 应用程序上下文)并指定您将注入哪个实现。

因此,您无需更改代码即可运行测试。看看这个答案