繁体   English   中英

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

[英]Does using annotations to inject dependencies remove the main benefit of dependency injection(external configuration)?

我正在使用 Spring,这里是 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,我应该更改 controller 以使用接口(?),如下所示:

@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
       }
}

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

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

然而,由于必须重新编译代码这一事实而失去了主要好处之一? 而如果我使用 xml 查找,我可以即时更改依赖关系?

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

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

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

那是正确的。 注释是源代码中的配置。 主要用于每个服务都有一个 class 的情况。 如果您对特定接口有多个实现,那么 XML 将是更好的选择。 您也可以将 XML 配置与注释混合使用。

我上次从 DI 阵营听到的传统方法是,在单元测试中,你不应该使用 DI 框架。 相反,只需自己实例化模拟服务并将其设置为主机 object

test()
    PersonController contr = new PersonController();
    contr.personService = new TestPersonService();
    // testing contr

这被誉为 DI 的第一个也是主要的成就,这让不明白的人(比如我)非常困惑。 请参阅我之前的批评: 使用 applicationcontext.getbean 与 @configurable 的优势

如果这个线程中的 DI 支持者反映了 DI 阵营的新趋势,他们不再那样做单元测试; 相反,测试也依赖于 DI,具有测试特定的 DI 配置。 那么它真的和服务定位器模式没有什么不同。 如果 DI 的主要特点是没有实际意义的,那有什么意义呢?

您的 controller class 完美地说明了这一点。 它不能在 Spring DI 框架之外作为 POJO 使用。 没有任何关于它的 POJO。 没有人在乎,这是理所当然的。 如果您的 class 依赖于服务定位器框架,则同样如此。

Spring beans 框架提供的其他功能,均不依赖于 DI; 它们也可以在服务定位器框架中实现。 很多人在捍卫DI设计模式时,其实是在捍卫Spring整个堆栈。 您实际上可以使用 Spring 作为服务定位器框架; Spring 现在不会做广告了,这是对其主要炒作点的打击; 但一旦炒作减弱,它就会吸引怀疑者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM