弹簧和接口 [英] spring and interfaces

查看:114
本文介绍了弹簧和接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到了关于Spring如何鼓励您在代码中使用接口的地方。我没有看到它。 spring xml配置中没有接口概念。 Spring的哪一部分实际上鼓励您使用接口(除了文档)?

I read all over the place about how Spring encourages you to use interfaces in your code. I don't see it. There is no notion of interface in your spring xml configuration. What part of Spring actually encourages you to use interfaces (other than the docs)?

推荐答案

为类定义接口时,它有助于依赖注入。你的Spring配置文件中没有关于接口的任何东西 - 你只需要输入类的名称。

When you define an interface for your classes, it helps with dependency injection. Your Spring configuration files don't have anything about interfaces in them themselves -- you just put in the name of the class.

但是如果你想注入另一个类提供等效功能,使用界面确实有帮助。

But if you want to inject another class that offers "equivalent" functionality, using an interface really helps.

例如,说你有一个分析网站内容的课程,你注入了它弹簧。如果您注入的类知道实际的类是什么,那么为了更改它,您将不得不更改大量代码以使用不同的具体类。但是如果您创建了一个 Analyzer 界面,那么您可以轻松地注入原始 DefaultAnalyzer ,因为您可以模拟 DummyAnalyzer 甚至是另一个基本相同的东西,比如 PageByPageAnalyzer 或其他任何东西。为了使用其中一个,你只需要更改你在Spring配置文件中注入的类名,而不是通过你的代码更改类。

For example, saying you've got a class that analyzes a website's content, and you're injecting it with Spring. If the classes you're injecting it into know what the actual class is, then in order to change it out you'll have to change a whole lot of code to use a different concrete class. But if you created an Analyzer interface, you could just as easily inject your original DefaultAnalyzer as you could a mocked up DummyAnalyzer or even another one that does essentially the same thing, like a PageByPageAnalyzer or anything else. In order to use one of those, you just have to change the classname you're injecting in your Spring config files, rather than go through your code changing classes around.

在我真正开始看到它的用处之前,它花了我一个半个项目。就像大多数事物(在企业语言中)最终有用一样,一开始似乎是毫无意义的工作,直到你的项目开始增长,然后你通过做更多的工作预先发现你节省了多少时间。

It took me about a project and a half before I really started to see the usefulness. Like most things (in enterprise languages) that end up being useful, it seems like a pointless addition of work at first, until your project starts to grow and then you discover how much time you saved by doing a little bit more work up front.

这篇关于弹簧和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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