2016-04-25 11 views
1

私はSpringでautowiredされているプレーンなPOJOを持ち、そのプロパティは持続しているようです。Spring Beanのプロパティが永続する

私は幸せなパスがOKであることを確認します。 - Beanのプロパティを設定して戻ります。ただし、私が幸せなパスにいなくても、プロパティ(この場合はresponseCode)を設定したくない場合は、以前の値に設定されています(コールが成功したとき)。

私はこの値を設定しないで、モデルで現在指定している値と同じにします。

私は、次のPOJOプロトタイプ豆

package com.uk.jacob.model; 

import org.springframework.context.annotation.Scope; 
import org.springframework.stereotype.Component; 

@Component 
@Scope("prototype") 
public class Website { 
    public String url; 
    public boolean response; 
    public int responseCode = 0; 
} 

私はそれがRestController

package com.uk.jacob.controller; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.bind.annotation.RestController; 

import com.uk.jacob.model.Website; 
import com.uk.jacob.service.PingerService; 

@RestController 
@RequestMapping("api/v1/") 
public class PingController { 

    @Autowired 
    PingerService pingerService; 

    @RequestMapping(value = "ping", method = RequestMethod.GET) 
    public Website getPing(@RequestParam String url){ 
     return pingerService.ping(url); 
    } 

} 

答えて

0

という事実から呼び出されるサービスクラス

package com.uk.jacob.service; 

import java.net.HttpURLConnection; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Component; 

import com.uk.jacob.adapter.HttpAdapter; 
import com.uk.jacob.model.Website; 

@Component 
public class PingerService { 

    @Autowired 
    HttpAdapter httpAdapter; 

    @Autowired 
    Website website; 

    public Website ping(String urlToPing) { 
     website.url = urlToPing; 

     try { 
      HttpURLConnection connection = httpAdapter.createHttpURLConnection(urlToPing); 

      website.response = true; 
      website.responseCode = connection.getResponseCode(); 
     } catch (Exception e) { 
      website.response = false; 
     } 

     return website; 
    } 
} 

内の情報だ設定していていますあなたのWebsite beanは@Scope("prototype")です。これは、毎回このBeanの作成時に別のBeanへの依存として注入されると、新しいインスタンスが作成されて注入されます。この場合、PingerServiceWebsiteの新しいインスタンスを取得します。たとえばWebsiteWebsite2という別のBeanにも注入されていると、異なる(新しい)インスタンスが注入されます。

Websiteが呼び出されるたびにWebsiteが新規である場合は、Websiteのプロトタイプアノテーションではこれを行うことはできません。コンテキストを公開してApplicationContext#getBean("website")を呼び出す必要があります。

+0

'ApplicationContext#getBean(" website ")についてもっと詳しく説明できますか?それはなんですか?私のコードの問題は何ですか? –

0

ご利用の際には、リクエストごとにウェブサイトBeanの新しいインスタンスが必要であることをご理解いただきますようお願いいたします。

@Scope( "request")を使用してください。

プロトタイプスコープは、どこから見てもウェブサイトのオートワイヤリングごとに別のインスタンスを作成することを意味します。たとえば、PingerServiceは独自のWebサイトBeanを持ち、同じAutowiringを持つ他のクラスでは共有されませんが、その値はPingerServiceのHTTP要求を超えて保持されます。

関連する問題