Sumit
Sumit

Reputation: 550

Spring: How to ignore RequestMappings found in a Controller's super class?

Let me first explain the setup that I have.

My web application consists of multiple modules which are interlinked in a way that Module 1 uses controllers / services from Module 2 to recreate common functionality and hence remove code redundancy. So simply put, 2 separate web applications with all classes from 1 application included as a jar in the other.

Now, the issue that I am facing is due to common URL mappings in the sub-module as per the following scenario:

Controller A from Module 1 extends Controller B from Module 2

package com.module1;

@RequestMapping("/client")
public class A extends B {

    @RequestMapping("/hello")
    public void helloWorldNew(...) {
        ...
    }
}



package com.module2;

@RequestMapping("/user")
public class B {

    @RequestMapping("/")
    public void helloWorld(...) {
        ...
    }
}

Controller C from Module 1 extends Controller D from Module 2

package com.module1;

@RequestMapping("/client")
public class C extends D {

    @RequestMapping("/helloworld")
    public void helloWorldNew(...) {
        ...
    }
}



package com.module2;

@RequestMapping("/human")
public class D {

    @RequestMapping("/")
    public void helloWorld(...) {
        ...
    }
}

As you can see, taking Module 2 separately, URLs that have been mapped are /user/ & /client/ which is legal in every sense. Now when Module 1 comes into the picture, as expected Spring throws an exception saying the URL /client/ is already mapped via A.helloWorld() and C.helloWorld() mappings.

Is there a way around this? Can I ask Spring to simply ignore the method-level RequestMappings found in the super class? Or is there a way I can hack Spring to ignore / override the mappings (just like the root-level RequestMappings did)?

Any help will be greatly appreciated.

Thanks,
Sumit

Upvotes: 0

Views: 2451

Answers (1)

Biju Kunjummen
Biju Kunjummen

Reputation: 49915

I can think of a couple of ways to do this:

When you are setting up your module 1, you can do a component scan for only packages that are relevant to you in module 1 (this assumes that the package names are different in module 1 and module2:

<context:component-scan base-package="package1, package2" use-default-filters="false">
</context:component-scan>

if the package names are not very different, you can try excluding by the class name pattern:

<context:exclude-filter type="regex" expression="*.Module1Class"/>

A second approach can be to declare the base classes in module 2 abstract, this way the controller corresponding to the base class will not be created at all.

A third approach, if the base classes are not that important to you, could be to put @RequestMapping which does not collide at all with the RequestMappings that are specified for the module 1.

Upvotes: 2

Related Questions