2017-05-18 43 views
-1

在我的Spring MVC应用程序中,我们遇到了以下问题。我们是春季新手,并使用spring 3.x.请解释下面的问题,如果不明确,请评论。Spring MVC应用程序不同步

  • 当我们在触发同时下面的服务和 库豆,在以下代码中所示的SampleBean对象越来越 与后触发请求重写并发请求。

  • 换句话说,SampleBean在线程1中的值是变
    与SampleBean的值覆盖在线索2

骨架代码带注释如下。

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也是。您可以尝试将SampleBean范围从singleton更改为另一个。也许更好的方法是不使用SampleBean的实例变量,而是为MyService的每个updateDetailsToDB方法请求创建一个新实例。 - 感谢郝池

-1

其实你的设计是错误的,因为你使用的是实例变量。 但在MyService类中使用@Scope("prototype")或@Scope(“request”)(如果它是web应用程序),则可以使其工作。

+0

因为我在默认情况下在MyService中使用@Service,它将会是单身权利吗? – prabu

+1

@prabu你是对的。 MyService中的@Service默认为singleton,SampleBean也是如此。您可以尝试将SampleBean范围从singleton更改为另一个。也许更好的方法是不使用SampleBean的实例变量,而是为MyService的每个'updateDetailsToDB'方法请求创建一个新实例。 – HaoChih

+0

对不起添加原型.. – DineshPandian