簡體   English   中英

春季:將對象從應用程序傳遞到RestController

[英]Spring: Pass object to RestController from Application

因此,我正在忙着編寫Spring Boot應用程序,但似乎無法找出如何將對象從主應用程序傳遞給RestController的方法。

這是我的Application.java:

@SpringBootApplication
@ComponentScan("webservices")
public class Application {


    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        Application app = new Application(ctx);
        LinkedBlockingQueue<RawDate> queue = new LinkedBlockingQueue<>();
        // do other stuff here
    }
}

這是我的RestController:

@RestController
public class GoogleTokenController {
    private LinkedBlockingQueue<RawData> queue;

    @CrossOrigin
    @RequestMapping(value = "/google/token", method = RequestMethod.POST, headers = {"Content-type=application/json"})
    @ResponseBody    
    public String googleToken(@RequestBody AuthCode authCode) {
        System.out.println("CODE: " + authCode.getAuthCode());
        // do other stuff here
        return "OK";
    }
}

因此,我想將在Application類中創建的LinkedBlockingQueue<RawData>實例傳遞給GoogleTokenController類。 但是我不知道該怎么做,因為spring會自動創建GoogleTokenController類。

請注意,我是Spring的新手。 謝謝。

制作要傳遞Spring Bean的對象,然后讓Spring將其注入到控制器中。 例如:

@SpringBootApplication
@ComponentScan("webservices")
public class Application {

    @Bean
    public LinkedBlockingQueue<RawDate> queue() {
        return new LinkedBlockingQueue<>();
    }

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        Application app = new Application(ctx);
        // do other stuff here
    }
}

@RestController
public class GoogleTokenController {
    @Autowired // Let Spring inject the queue
    private LinkedBlockingQueue<RawData> queue;

    @CrossOrigin
    @RequestMapping(value = "/google/token", method = RequestMethod.POST, headers = {"Content-type=application/json"})
    @ResponseBody    
    public String googleToken(@RequestBody AuthCode authCode) {
        System.out.println("CODE: " + authCode.getAuthCode());
        // do other stuff here
        return "OK";
    }
}

在需要訪問queue其他地方,也讓Spring注入它。

如何創建可注入控制器的組件? 您可以為Queue創建一個單獨的類,如下所示:

@Component
public class RawDateQueue extends LinkedBlockingQueue<RawDate> {
    // no further implementations
}

並在Controller中使用RawDateQueue。

采用 -:

  @autowired 
   private LinkedBlockingQueue<RawData> queue;

    OR

   @inject 
   private LinkedBlockingQueue<RawData> queue;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM