ApplicationContext with same bean having @RequestM

2019-09-17 13:39发布

In my applicationContext.xml I have 2 beans with same class and different id(test and test1). The application context gets loaded correctly, but when I add @RequestMapping to one method then the bean creation fails with the below error. This used to work with AnnotationMethodHandlerAdapter but its failing with RequestMappingHandlerMapping and RequestMappingHandlerAdapter.

Error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'test1' bean method 
public java.lang.String com.test.render()
to {[/render],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'test' bean method

Please suggest how to fix this.

Code:

applicationContext.xml

 <bean id="test" class="com.abc.test" />

 <bean id="test1" class="com.abc.test" />

Controller

@Controller
 @RequestMapping( value ={"/test/", "/test1/"})
public class test {

    @RequestMapping("render")
    public String render ()
    {
        //some code here.
    }
}

2条回答
姐就是有狂的资本
2楼-- · 2019-09-17 13:59

I could find a work around with this. This solution if for the comments I posted on 21-May

I used order property to instantiate the custom defined RequestMappingHandlerMapping in the xml file and it worked!! It took my custom defined RequestMappingHandlerMapping instead of the default one loaded by <annotation-driven>.

查看更多
该账号已被封号
3楼-- · 2019-09-17 14:19

You can do it like this... switch from singleton approach to prototype and inside the xml do

While programmatically define

    class P1 {
       @Autowire
       NotSoSingleton prototypedBean;
    }

    class P2 {
       @Autowire
       NotSoSingleton prototypedBean;
    }

    class P3 {
       @Autowire
       NotSoSingleton prototypedBean;
    }

Would this approach do?

查看更多
登录 后发表回答