2016-07-06 3 views
-1

私はSpring Bootアプリケーションを書くのに忙しいですが、メインアプリケーションからRestControllerにオブジェクトを渡す方法を見つけることができません。ここでSpring:アプリケーションから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クラス。しかし、春は自動的にGoogleTokenControllerクラスを作成するので、私はそれをどうするかわかりません。

ご注意ください私は非常に春に新しいです。ありがとう。

答えて

2

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にそれを注入させます。

+0

こんにちはおかげで、私はこれを行う場合GoogleTokenControllerでキュー変数がnullです。 –

+0

@ArmandMareeあなたは 'GoogleTokenController'を' new GoogleTokenController() 'で自分で作成していますか?それをしないでください(これはSpringの依存性注入で人々が作る1番の間違いです) - Springに 'GoogleTokenController'を作成させてください。 – Jesper

+0

いいえGoogleTokenControllerを作成していません。春はそれだけでそれを行います。 –

0

コントローラに注入できるコンポーネントを作成する方法はありますか?あなたは、キューのための別のクラスを作成することができます

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

あなたのコントローラでRawDateQueueを使用してください。

0

使用 - :答えを

@autowired 
    private LinkedBlockingQueue<RawData> queue; 

    OR 

    @inject 
    private LinkedBlockingQueue<RawData> queue; 
+1

あなたの答えにいくつかの説明を加えてください。コードオンリーの回答はお勧めできません。ありがとうございました。 –

関連する問題