重复的@Autowired bean块(Duplicated blocks of @Autowired beans)

系统教程 行业动态 更新时间:2024-06-14 16:57:17
重复的@Autowired bean块(Duplicated blocks of @Autowired beans)

我有一个spring MVC应用程序。 应用程序的每个控制器都会自动连接它需要与之交互的@Service组件。 Sonarqube分析检测到存在一些重复:一些控制器可能使用相同的服务,在这种情况下,@ @Autowired注释和相应的字段确实相同。

例如,以下内容将在许多控制器中重复:

@Autowired private FooService fooService; @Autowired private BarService barService;

这是一个小问题,我不知道是否应该解决这个问题。 由于我的所有控制器都继承了一个AbstractController ,并且所有服务都是单例,所以在受保护的字段中将所有@Autowired元素放在基类中是否有意义?

I have a spring MVC application. Each controller of the application auto-wires the @Service components it needs to interact with. A Sonarqube analysis has detected that there was some duplication in this: some controllers may use the same services, in which case the @Autowired annotation and the corresponding fields are indeed the same.

For instance, the following would be duplicated in many controllers:

@Autowired private FooService fooService; @Autowired private BarService barService;

This is a minor issue, and I don't know whether/how I should address this. Since all my controllers inherit an AbstractController, and all services are singletons, would it make sense to put all @Autowired elements in the base class, in protected fields?

最满意答案

如果依赖项已经在子类中,那么您可能有理由,例如它们在概念上不属于抽象类。 如果是这样,请将它们保留在子类中。

遵守DRY原则很重要,但不要对它充满狂热。 复制代码为您提供了灵活性,类依赖性是您需要这种灵活性的典型位置。 更不用说代码更简单了这种重复。

静态代码分析有助于提供改进代码的指针,但不应盲目追随它们。

If the dependencies already are in the subclasses, you probably have a reason for that, e.g. they do not conceptually belong in the abstract class. Keep them in the subclass if so.

It's important to adhere to the DRY principle, but don't be fanatic about it. Duplicating code gives you flexibility, and class dependencies are a typical place where you want such flexibility. Not to mention that the code is simpler with such duplication.

Static code analysis is good for providing pointers to improve your code, but they shouldn't be followed blindly.

更多推荐

本文发布于:2023-04-12 20:02:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/d6b145443624eba37b23415c16fbdc7a.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:bean   Autowired   Duplicated   beans   blocks

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!