注释是否也可以将代码与 Spring 等框架结合起来?
不鼓励扩展基于 Spring 的接口,因为它不必要地将代码与 Spring 耦合。同样的推理也适用于注释吗?在使用它们之前,我们需要将它们导入到源代码中。
Extending spring based interfaces is discouraged as it unnecessarily couples the code with Spring. Does the same reasoning applies to annotations as well? We need to have them imported in the source code before using them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将采取相反的观点——当然,使用 Spring 特定的注释将类与 Spring 联系起来。我认为导入和使用 Spring 注释将代码与 Spring 联系起来是不言而喻的(尽管您可以为非 Spring 环境轻松地重新定义这些注释)。对我来说关键是它与 Spring 的联系有多深。
检查和处理注释比重构类层次结构或复制非标记接口的功能更容易。假设您想保留注释,并且可以复制注释背后的逻辑,那么这样做(IMO)比重新创建实现类似功能的任何类/接口层次结构更容易。
另一个关键是“不必要”二字。我尚未创建 Spring 应用程序,并且需要 Spring 环境之外的这些类。当我有(通常对于公开的 API)时,它处于接口级别。但请注意,我从一开始就知道这种曝光将会存在,并且我做了相应的计划。
I'll take the opposite viewpoint--of course using a Spring-specific annotation ties the class to Spring. I claim it's self-evident that importing and using Spring annotations ties the code to Spring (although you could trivially redefine those annotations for a non-Spring environment). The key for me is how deeply it's tied to Spring.
It's easier to check for, and process, annotations, than it is to restructure a class hierarchy or duplicate the functionality of a non-marker interface. Assuming you wanted to leave the annotations in, and could duplicate the logic behind the annotations, it'll be easier to do that (IMO) than to recreate whatever class/interface hierarchy implemented similar functionality.
The other key is the word "unnecessarily". I have yet to create a Spring application and need those classes outside of a Spring environment. When I have (generally for exposed APIs) it's been at the interface level. Note, however, that I knew from the onset that this exposure would exist and I planned accordingly.
大多数人会认为事实并非如此。虽然您已经导入了确保 Spring 处理请求或包装事务所需的注释,但您并没有扩展或实现特定的类或接口。
这样想一下,当您注释该类时,您是在告诉 Spring 根据您的配置执行各种操作。去掉这些注释,你得到的就是一个只有一些方法的 POJO。如果没有这些注释,它是一个完全有效的对象,它可能不会执行您希望它执行的操作(即处理请求),但代码仍然执行与注释相同的逻辑 - 您现在负责适当地调用它。
Most would argue that this does not. While you've imported those annotations needed to ensure that Spring handles the request or wraps the transactions, you are not extending or implementing a specific class or interface.
Think about it this way, when you've annotated that class you're telling Spring to do various things based upon your configuration. Take out those annotations, and what you have is a POJO which just has some methods. It's a completely valid object without those annotations, it might not do what you wish it do (i.e. handle requests), but the code is still performing the same logic as it was with the annotations -- you are just now responsible for calling it appropriately.