2017-05-18 3 views
-1

스프링 MVC 애플리케이션에 다음과 같은 문제가 있습니다. 우리는 봄에 익숙하며 봄 3.x를 사용합니다. 아래의 문제를 설명해 드리겠습니다. 명확하지 않은 경우 의견을 남기십시오. 스프링 MVC 애플리케이션이 동기화되지 않았습니다.

  • 우리는 서비스와 저장소 콩 아래, 아래 코드에 표시된 SampleBean 개체가 나중에 트리거 요청을 무시 을 받고하는 동시에 동시 요청을 트리거

    . 의견은 다음과 같이 즉

  • 는 스레드 1의 SampleBean의 값은 스레드에 2

스켈레톤 코드를 SampleBean의 값을 오버라이드 (override)
을 받고있다.

MyService.java

@Service public class MyService { 
     @Autowired private SampleBean sampleBean; 
     @Autowired private MyDao myDao; 
     public void updateDetailsToDB() throws Exception { 
      sampleBean.setXXX("xxx"); 
      sampleBean.setYYY("yyy"); 
      myDao.updateDetailsToDB(sampleBean); 
     } 
    } 

MyDao.java

@Repository 
public class MyDao { 
    @Autowired private SampleBean sampleBean; 
    @Autowired private MyDao myDao; 
    public void updateDetailsToDB(SampleBean sampleBean) throws Exception { 
     //Step 1: Print the data in sampleBean to console - *At this point the the sampleBean object prints the correct value specific to the thread.* 
     //Step 2: Insert data to table 1 into db using **jdbcTemplate**, the data will be taken from the bean 
     sampleBean getters. 
     //Step 3: Print the data in sampleBean to console.- *At this point the sampleBean value always print the values of the second request and it overwrites the value of the bean in first request as well which is not the case in Step 1.* 
     //Step 4: Insert data to table 2 
    } 
} 

업데이트 : 내가 다음 서비스 클래스의 메소드 모든 일에를 동기화 추가하는 경우 요구 사항으로 잘 작동합니다. ests는 하나씩 처리됩니다. 을 동기화하지 않고이 문제를 해결하는 방법.

+0

당신은 싱글 톤으로 상태를 유지하면 안됩니다. 디자인에 결함이 있습니다. 'SampleBean'이 없어야합니다. 메소드 인수로서 존재해야하며,'@ ModelAttribute'로 주석 처리되는 것이 바람직합니다. –

답변

0

MyService의 @Service는 기본적으로 싱글 톤이며 SampleBean도 있습니다. Singleton에서 다른 Singleton으로 SampleBean 범위를 변경하려고 할 수 있습니다. 더 나은 방법은 SampleBean의 인스턴스 변수를 사용하지 않고 대신 MyService의 각 updateDetailsToDB 메소드 요청에 대해 새 인스턴스를 생성하는 것입니다. - 고마워요 HaoChih

-1

실제로 인스턴스 변수를 사용하기 때문에 디자인이 잘못되었습니다. MyAppvice 클래스에 @Scope("prototype") 또는 @Scope ("요청") (웹 앱 인 경우)를 사용하면 제대로 작동 할 수 있습니다.

+0

기본적으로 MyService에서 @Service를 사용하고있어 기본적으로 싱글턴이 될 것입니까? – prabu

+1

@ prabu 네 말이 맞아. MyService의 @Service는 기본적으로 싱글 톤이며 SampleBean도 동일합니다. Singleton에서 다른 Singleton으로 SampleBean 범위를 변경하려고 할 수 있습니다. 더 나은 방법은 SampleBean의 인스턴스 변수를 사용하지 않고, 대신 MyService의 각 updateDetailsToDB 메소드 요청에 대한 새 인스턴스를 생성하는 것입니다. – HaoChih

+0

죄송합니다. 프로토 타입을 추가하십시오 .. – DineshPandian

관련 문제