简体   繁体   中英

Can a Spring @RequestMapping-annotated method be static?

This is a follow-up question to a previous question .

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.

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:

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*?

* 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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