Spring @ RequestMapping注释的方法可以是静态的吗? [英] Can a Spring @RequestMapping-annotated method be static?

查看:376
本文介绍了Spring @ RequestMapping注释的方法可以是静态的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是针对上一个问题的后续问题

根据我的理解,一个 @Controller - 注释类与 @RequestMapping - 注释的方法不能成功从另一个继承,因为Spring无法识别它们都映射到相同的方法。即使Spring认识到他们是同一个实例,也没有办法决定使用两个控制器bean的哪个实例来调用该方法。

From what I understand, one @Controller-annotated class with @RequestMapping-annotated methods cannot successfully inherit from another because Spring can't recognize they're both mapping to the same method(s). Even if Spring recognized they were the same instance, it would have no way to decide which instance of the two controller beans to use to invoke the method.

但是静态方法独立于类的任何实例调用,子类不带有父类的静态成员的自己的副本。使所有的 @RequestMapping - 注释方法 static (至少在父类)可以解决这个问题,给我的问题:

But static methods are invoked independent of any instances of a class, and child classes do not carry their own copy of the parent's static members. Making all of my @RequestMapping-annotated methods static (at least on the parent class) could resolve this problem, which brings us to my question:

可以使用 public static 方法与 @Controller 对类和 @RequestMapping 上的方法?并且它的行为与非静态方法相同*?

Can a public static method be used with @Controller on the class and @RequestMapping on the method? And would it behave about the same as a non-static method*?

*我知道一个 static 方法自然不能访问实例成员,但是控制器通常应以这样的方式实现,即无论如何不存在任何实例变量。

* I know that a static method naturally can't access instance members, but controllers should typically be implemented in such a way that there aren't any instance variables anyway. All the methods I'm dealing with would work exactly the same if they were static methods, provided the framework allows for it.

推荐答案

它适用于我在Spring 3.2.X.虽然,控制器通常在其实例上有数据成员,但它们通常是服务的自动连接实例。所以我不知道你是否误解了Spring框架的整体设计模式。

It works fine for me in Spring 3.2.X. Though, controllers often have data members on their instances, but they're usually autowired instances that are services. So I wonder if you're misunderstanding the overall design pattern of the Spring framework.

我不能想到使用静态方法的任何真正的好处,控制器实例已经存在,所以即使你让控制器有所有的静态方法,它仍然会被实例化。我认为实例调用开销将是微不足道的,并在噪声中失去性能。

I can't think of any real benefit in using a static method, the controller instance is already there, so even if you made the controller have all static methods it's still going to get instantiated. I would think the instance invocation overhead would be minuscule and lost in the noise as far as performance.

这篇关于Spring @ RequestMapping注释的方法可以是静态的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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