2012-04-05 126 views
24

我想實現和春天有個購物車,所以我需要保存對象Cart(其中有同類產品,paymentType和deliveryType屬性)會話。我試圖用bean和屬性「scope」設置爲「session」來創建它,但它不起作用,我應該在我的控制器或類中使用一些額外的註釋嗎?任何示例用法都會非常有用:-)提前致謝。春存儲對象的會話

回答

26
@Component 
@Scope("session") 
public class Cart { .. } 

然後

@Inject 
private Cart cart; 

應該工作,如果是在網絡環境(調度員servlet.xml的)聲明。另一種選擇是使用原始的會話,並把你的車對象有:

@RequestMapping(..) 
public String someControllerMethod(HttpSession session) { 
    session.addAttribute(Constants.CART, new Cart(); 
    ... 
    Cart cart = (Cart) session.getAttribute(Constants.CART); 
} 
+0

是的,「替代選項」的作品,但我不想使用它。當我在我的控制器中創建一個私人屬性購物車時,我得到錯誤,「沒有匹配的bean發現依賴性:預計至少1有資格作爲這個依賴關係的autowire候選者的bean。依賴註釋:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}「。這個bean應該在applicationContext.xml中定義爲 tomaszf 2012-04-05 20:12:55

+1

沒有dispatcher-servlet.xml文件或者,像我展示 - 。聲明的註解 – Bozho 2012-04-05 20:23:56

+0

嗯,但是當我在調度-servlet.xml中使用註解,沒有bean定義,我得到我之前粘貼錯誤,再加上當我使用註釋並定義bean時,我只能用該控制器獲得404。 – tomaszf 2012-04-05 20:41:14

13

如果直接注射購物車到您的控制器,那麼問題可能發生,因爲你的控制器是單身作用域(默認) ,它比你注入的bean範圍更廣。這篇優秀的文章概括介紹了您正在嘗試做的四種方法:http://richardchesterwood.blogspot.co.uk/2011/03/using-sessions-in-spring-mvc-including.html

這裏是解決方案的快速摘要:

  1. 範圍控制器會話範圍(在控制器級別使用@scope("session")),只是在控制器的購物車實例。
  2. 控制器可以請求並注入會話範圍的購物車。
  3. 直接使用會話 - 有點混亂,國際海事組織。
  4. 使用Spring的註釋<aop:scoped-proxy/>

所有的方法都有其利弊。我通常選擇2或4選走4實際上是非常簡單,是我見過documented by Spring.的唯一方法

+0

正確的URL是http:// richardchesterwood。 blogspot.co.uk/2011/03/using-sessions-in-spring-mvc-including.html – Gilead 2012-10-17 15:52:20

+0

謝謝@Gilead。我更新了正確的網址。 – 2012-10-17 17:29:59

+0

請注意,在解決方案#4中,不要在任何方法中使用final。這樣做並且該訪問者將是單身人士,而不是會話範圍,因爲AOP不能攔截總決賽。 – 2013-11-26 06:08:31

2

你只需要與會話和代理模式如下添加註釋範圍

@Component 
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS) 
public class ShoppingCart implements Serializable{ 
} 

在哪裏無論你需要使用購物車對象,就可以自動裝配它

@Service 
public class ShoppingCartServiceImpl implements ShoppingCartService { 
    Logger logger = LoggerFactory.getLogger(ShoppingCartServiceImpl.class); 


    @Autowired 
    ShoppingCart shoppingCart; 
} 

披露:我已經開發了一個示例項目,它使用Spring MVC的,演示春季會議範圍angularJS和引導 -
https://github.com/dpaani/springmvc-shoppingcart-sample