“Ambiguous mapping found” when one @Controller extends another @Controller

前端 未结 1 1920
轻奢々
轻奢々 2021-01-14 12:26

I have a ImportAction class which serves as a parent class for several type-specific import controllers, such as ImportClientsAction and Impo

相关标签:
1条回答
  • 2021-01-14 12:48

    (Hat tip to Sotirios Delimanolis for helping me learn & understand this)

    One @Controller-annotated class should not extend another @Controller-annotated class, because the parent class's methods also exist on the child class.

    Each @Controller-annotated class is instantiated as a bean in the servlet context (?), and that instance of the class (ie that bean) is then used to call @RequestMapping-annotated methods according to the mapping provided when a user makes a request to the servlet.

    When you have two @Controller-annotated classes, one a child of the other, the child class tries to register the mappings on the parent a second time. "No big deal!" you say. The problem is that Spring has no way to definitively decide which instance to use to call the mapped method, even if it is exactly the same method.

    The same problem applies if you register two beans of the same type/class, where both try to register identical mappings.

    There's a couple ways that Spring using the wrong instance would be problematic:

    1. The child overrides the parent's methods. It doesn't even have to override the mapped methods, just a method called from a mapped method. The behavior for the child instance would be different than for the parent instance, so they can't have the same mapping.
    2. The class has non-static fields. This applies even if two beans are the same class. One instance/bean can have different values and thus different behavior due to the values of the instance fields.

    Because of these problems (and probably several others), Spring cannot ignore or work around duplicate mappings, even if the method that's mapped to is the same method.

    In a related question, I tried working around this by making the @RequestMapping-annotated methods static. Problem 1 still applies, so simply making each mapped method static doesn't fix or work around the problem.

    0 讨论(0)
提交回复
热议问题