2016-07-17 30 views
2

私はSpringには新しく、最近テストRESTful Webサービスアプリケーションを作成しました。 私は豆を注入する春@Autowiringの方法に従っています。以下は私のコードと質問です:Springオートワイヤリングとスレッドセーフ

@Service 
public class HelloWorld {  

    @Autowired 
    private HelloWorldDaoImpl helloWorldDao; 

    public void serviceRequest() { 
     helloWorldDao.testDbConnection(); 
    } 

} 

@RestController 
public class HelloWorldController { 

    @Autowired 
    private HelloWorld helloWorld; 

    @RequestMapping(value = "/test", method = RequestMethod.POST) 
    public String test() { 
     helloWorld.serviceRequest(); 
     return "Success"; 
    } 
} 

今、私の質問は、どのように我々は確実んが、私は2つの要求を同時に正確に来て、彼らの両方が同じサービスクラス変数「のhelloWorld」を共有している持っているとき、ありますリクエスト1に返された値はリクエスト2に返されず、その逆もあります。

@Autowiredを使用すると、Springはこのようなマルチスレッド問題を自動的に処理しますか?

答えて

0
  • 基本的に、HTTPリクエストはペアで動作しますが、リクエストごとに応答basic explanation about httpがあります。 2つの要求について
  • 同時にthis also may help
  • のSpring Bean(HelloWorldの)は、デフォルトlook hereによってシングルトンであるので、これを正確にコードは、本質的に
1

春んではない同じ結果を返します。は、特に完全に異なるレイヤーで発生するため、アプリケーションのスレッドの安全性を考慮してください。 Autowiring(とSpringプロキシ)はそれとは関係ありません。それは、従属コンポーネントを作業全体にアセンブルするためのメカニズムです。

あなたが提示した両方の豆が効果的に不変であるため、あなたの例はあまり代表的ではありません。同時リクエストによって再利用される可能性のある共有状態はありません。春 - もしあなたがストレステストあなたは、遅かれ早かれ、エラーメッセージを取得することが保証している。このエンドポイント

@Service 
public class FooService {  
    // note: foo is a shared instance variable 
    private int foo; 

    public int getFoo() { 
     return foo; 
    } 

    public void setFoo(int foo) { 
     this.foo = foo; 
    } 
} 

@RestController 
public class FooController { 

    @Autowired 
    private FooService fooService; 

    @RequestMapping(value = "/test") 
    public String test() { 
     int randomNumber = makeSomeRandomNumber(); 
     fooService.setFoo(randomNumber); 
     int retrievedNumber = fooService.getFoo(); 
     if (randomNumber != retrievedNumber) { 
      return "Error! Foo that was retrieved was not the same as the one that was set"; 
     } 

     return "OK"; 
    } 
} 

:それは本当に春はあなたのためのスレッドの安全性を気にしない説明するためには、次のコードを試みることができますあなたが足で自分を撃ってしまうのを防ぐために何もしません。

関連する問題