简体   繁体   中英

RequestMapping works on private methods

Now, my understanding, in general, is that @RequestMapping methods need to be public. Can they also be private? If so when would we use this?

The reason why I am asking this is that I noticed that @RequestMapping worked on private methods as well. Why is this so?

Is it because spring access these methods through reflections so access modifiers aren't really considered? Is this a bug or a feature that has uses?

Now the real reason (if one exists) is hard to say without getting into the heads of the Spring developers, and because this was implemented quite a while ago.

I would guess that this was an oversight, as there's not a significant advantage in using private methods as targets for request mapping. Sure, you can't call them from your other code anymore, but if you're calling controller methods from your code, you deserve all the problems you get.

This link describes an interesting situation where the request mapping works for a package private method, but since AOP only works for public methods the result is confusion and destruction. There's also 4 (four!) places given where a fix could be applied to prevent non-public methods from being targets of @RequestMapping .

So I would classify this as a (minor) bug. Now it's up to the programmers to stay on their toes and remember to make those methods public. I'll see if I can find an existing bug ticket for this.

As responded by pivotal in the JIRA ISSUE

This indeed works as designed. We generally don't restrict visibility declarations on reflective methods, leaving that choice up to the developer. That said, for this particular case, I would recommend public declarations or potentially package-visible declarations (without a visibility keyword), with private handler methods actually being more of a niche effect here.

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