2016-07-28 19 views
0

Alle meine Controller (RequestMapping URL) beginnen mit der gleichen Variablen.beste Möglichkeit zum Erstellen einer globalen Variablen in Spring MVC

myController/blablabal 

Ich denke an eine globale Variable zu schaffen „MyController“ so in der Zukunft zu ersetzen, wenn ich die URL-Namen zu ändern, ich brauche nur an einer Stelle zu ändern. Die Art, wie ich dies gerade mache, ist eine Bean zu erstellen. My Bean-Konfigurationsdatei:

<bean id="controllerURL" class="java.lang.String"> 
    <constructor-arg type="String" value="tt"/> 
</bean> 

Da ist in meinem Controller:

@RequestMapping(value ="/${controllerURL}/qrcode/blablbal", method = RequestMethod.GET) 

Allerdings scheint es, dass ich nicht diese Variable controllerURL richtig zugreifen kann. Fehle ich hier etwas? Oder haben wir eine bessere Möglichkeit, eine globale Variable in Spring MVC zu erstellen?

Antwort

1

Erstellen Sie eine Konstante und verwenden Sie sie. Der Compiler wird die Konstante und die verbleibende URL zur Kompilierungszeit zusammenführen.

public class MyConstants { 
    public static final String PATH_PREFIX = "/myController/blablabal"; 
} 
import MyConstants.PATH_PREFIX; 

@Controller 
public class MyController { 
    @RequestMapping(path = PATH_PREFIX + "/qrcode/blablbal", method = RequestMethod.GET) 
    // method here 
} 
+0

Das, warum ich about..but ich dachte möchte wirklich lernen, wie man eine Bean als globale Variable erstellt. – user3369592

1

können Sie globale Variable erstellen Bohne mit wie unten.

1.In Ihre Bohne Erklärung,

Verwenden java.lang.Stringstatt von String in Konstruktor type-Attribut.

<bean id="controllerURL" class="java.lang.String"> 
    <constructor-arg type="java.lang.String" value="tt"/> 
</bean> 
  1. In Ihrem -Controller,

    @Autowired String controllerURL;

und

@RequestMapping(value = controllerURL +"/qrcode/blablbal", method = RequestMethod.GET) 
+0

Wenn ich das versuchte, sagte es Attribut muss konstant sein. Ich glaube, controllerURL muss "statisch final" sein. – user3369592

+0

möglicherweise wahr, ich schrieb Pseudocode in meiner Antwort. –

+0

Wenn es "statisch final" sein muss, muss es wahrscheinlich initialisiert werden. – user3369592

2

ich eine Base mit der Basis-URL erstellen würde

import org.springframework.web.bind.annotation.RequestMapping; 


@RequestMapping("/base") 
public class BaseController { 
} 

und implementieren es

import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController; 


@RestController 
public class MyController extends BaseController{ 

    @RequestMapping("/hello") 
    String hello(){ 
     return "Hello"; 
    } 
} 
Verwandte Themen