[英]Using scope proxy for shopping cart in Spring boot App
I have a spring boot app where there is a shopping cart feature.我有一个 spring 启动应用程序,其中有购物车功能。 And I use scope proxy to store shopping cart item.
我使用 scope 代理来存储购物车项目。 The problem is that the shopping cart is always empty when I try to retrieve it.
问题是当我尝试检索时购物车总是空的。
Here is my ShoppingItem class:这是我的 ShoppingItem class:
@Data
@AllArgsConstructor
public class ShoppingItem {
private String productId;
private String quantity
}
My ShoppingCart class:我的购物车 class:
public class ShoppingCart extends ArrayList<ShoppingItem> implements Serializable {
}
My spring configuration class where I declare ShoppingCart bean:我的 spring 配置 class 我声明 ShoppingCart bean:
@Configuration
public class MvcConfig {
....
@Bean
@Scope(
value = WebApplicationContext.SCOPE_SESSION,
proxyMode = ScopedProxyMode.TARGET_CLASS
)
public ShoppingCart shoppingCart(){
return new ShoppingCart();
}
}
My ShoppingCartService class:我的购物车服务 class:
@Service
public class ShoppingCartService {
@Autowired
private ShoppingCart shoppingCart;
public void add(String productId){
// quick breakpoint check, I can see that product has been added
shoppingCart.add(new ShoppingItem(productId, 1));
}
public int size(){
return shoppingCart.size();
}
}
My ProductController class:我的产品控制器 class:
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
private ShoppingCartService shoppingCartService;
@PostMapping("/add-to-cart")
public String addToCart(@PathVariable("productId") String productId){
shoppingCartService.add(productId);
....
return "return-to-a-page";
}
}
And finally my ShoppingCartDetailsController:最后是我的 ShoppingCartDetailsController:
@Controller
@RequestMapping("/product")
public class ShoppingCartDetailsController {
@Autowired
private ShoppingCartService shoppingCartService;
@GetMapping("/get-shopping-cart")
public String getShoppingCart(....){
// this return zero :(
System.out.println("Shopping Cart content : " + shoppingCartService.size());
....
return "return-to-a-page";
}
}
Thanks for your help!谢谢你的帮助!
Ok, I fix my bug by putting the scope on the service and not on the component.好的,我通过将 scope 放在服务上而不是组件上来修复我的错误。 Everything work like a charm now
现在一切都像魅力一样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.