1

次のような1つのリクエストマッピングを定義する親クラスPがあります。

public abstract class P {
 @RequestMapping(value = "/a/b/c", method = RequestMethod.POST)
    public String productLink(@RequestParam("abc") String json) throws Exception {
        return getProductLinks(json);
    }
}

私には子供向けのControllerクラスがいくつかありClassImpl、そのうちの1つです。

@Controller
public class ClassImpl extends P {
@RequestMapping(value = "/start", method = RequestMethod.GET)
    public String start(@RequestParam(value = "keyword", required = true) String keyword,
            @RequestParam(value = "keywordId", required = true) long keywordId) throws Exception {
     //Something
    }
}

このアプリを1つの子クラスのみで実行すると、正常に動作しますが、複数の子コントローラーで問題が発生します。

アプリケーションを実行すると、次のようなエラーが発生します"Cannot map handler ClassImpl to URL path [/a/b/c]: There is already handler [a.b.c.d.ClassImpl@a92aaa] mapped"

It seems that because of multiple child classes, it is unable to find the controller for this mapping which is understood.

@RequestMapping各クラス(または1つの別々のクラス)で定義することが唯一の方法ですか?私はすべての場所に同様のコードを置きたくありません。親クラスに保持して使用し続けるための回避策はありますか?

ありがとう、

4

2 に答える 2

0

各クラス(または1つの個別のクラス)で@RequestMappingを定義することが唯一の方法ですか?

簡単な答えはイエスです。個人的には別のクラスに属していると思います。

productLink()とにかく、なぜ親クラスに入れたいのですか?これは抽象的なメソッドではなく、オーバーライドしていないので、私にはあまり意味がありません。

于 2013-01-30T18:33:38.123 に答える
0

抽象クラスで @RequestMapping を使用しないでください。このアノテーションは実際のコントローラー用なので、具象クラスです。

Abstract クラスは、意図したとおりに使用します。つまり、作業を行うためではなく、コードを因数分解するために使用します。

ここで次のようなことができます:

public abstract class P {

    public String productLink(String json) throws Exception {
       return getProductLinks(json);
    }
}

その後

@Controller
public class ClassImpl extends P {

    @RequestMapping(value = "/start", method = RequestMethod.GET)
    public String start(@RequestParam(value = "keyword", required = true) String keyword,
        @RequestParam(value = "keywordId", required = true) long keywordId) throws     Exception {
         //Something
    }

    //here reusing the code from superclass
    @RequestMapping(value = "/a/b/c", method = RequestMethod.POST)
    public String productLink(@RequestParam("abc") String json) throws Exception {
        return super.getProductLinks(json);
    }
}

これにより、定型コードが少し追加されますが、これが私見の方法です。

于 2013-01-30T15:56:39.327 に答える