使用注释注入依赖项是否会消除依赖项注入的主要好处(外部配置)? [英] Does using annotations to inject dependencies remove the main benefit of dependency injection(external configuration)?

查看:123
本文介绍了使用注释注入依赖项是否会消除依赖项注入的主要好处(外部配置)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring,这是一个控制器:

I am using Spring, here is a controller:

@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,我应该更改控制器以使用接口(?),如下所示:

However, to properly make use of DI I should change the controller to make use of an interface (?) like so:

@Controller
public class PersonController {

@Resource(name="personService")
private IPersonService personService; //Now an interface
}

然后,这将允许我使用两项服务一项测试,一项现场直播。我可以通过在服务上添加/删除注释来更改:

This would then allow me, for example, to use two services one test and one live. Which I could alter by adding/removing the annotation on the services :

@Service("personService") // this line would be added/removed
@Transactional
public class LivePersonService implements IPersonService {

    public List<Person> getAll() {
        //do whatever
       }
}

@Service("personService") //this line would be added/removed
@Transactional
public class TestPersonService implements IPersonService {

    public List<Person> getAll() {
        //do something else
       }
}

但是由于必须重新编译代码而失去了主要好处之一?而如果我使用xml查找,则可以即时更改相关性?

However one of the main benefits is lost due to the fact that the code has to be recompiled ? Whereas if I used xml lookup I could alter the dependency on-the-fly ?

推荐答案

配置仍然是外部的,因为它在外面,您可以定义要注入的实现。在类内部,您只需对类所依赖的 名称 进行硬编码(没关系,因为这种依赖关系是

The configuration is still external, because it is outside where you define which implementation is going to be injected. Inside the class, you just hardcode the "name" of something the class depends on (which is ok, because this dependency is inherent to the class).

这表示,您可以使用XML覆盖代码的注释以执行测试(您将拥有特定的XML

This said, you can use XML to override the annotations of your code for the tests execution (you would have a specific XML application context for your tests) and specify which implementation you will inject.

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

Therefore, you don't need to change your code to run the tests. Take a look to this answer.

这篇关于使用注释注入依赖项是否会消除依赖项注入的主要好处(外部配置)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆