Appearance
@Scope 注解的使用场景
这个注解默认是单例方式,既 singleton,在Spring容器中该实例唯一;还有其他的作用域范围,演示一下大概的使用。
示例
业务场景示例
1. 购物车场景(Prototype 作用域)
@Component
@Scope("prototype")
public class ShoppingCart {
private List<String> items = new ArrayList<>();
public void addItem(String item) {
items.add(item);
}
public List<String> getItems() {
return items;
}
}
@Service
public class OrderService {
@Autowired
private ApplicationContext applicationContext;
public void processOrder(Long userId) {
// 每个用户需要独立的购物车实例
ShoppingCart cart = applicationContext.getBean(ShoppingCart.class);
cart.addItem("商品1");
cart.addItem("商品2");
// 处理订单逻辑...
}
}场景说明:每个用户的购物车应该是独立的,不能共享,因此使用 prototype 作用域。
2. 请求上下文信息(Request 作用域)
@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestContext {
private String requestId;
private Long userId;
@PostConstruct
public void init() {
this.requestId = UUID.randomUUID().toString();
// 从请求中获取用户ID
this.userId = getUserIdFromRequest();
}
// getters...
}
@Service
public class AuthService {
@Autowired
private RequestContext requestContext;
public void checkPermission() {
// 使用当前请求的用户ID进行权限检查
Long currentUserId = requestContext.getUserId();
// 权限检查逻辑...
}
}场景说明:每个 HTTP 请求需要独立的上下文信息,如请求ID、用户信息等。
3. 用户偏好设置(Session 作用域)
@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserPreferences {
private String theme;
private String language;
// getters and setters...
}
@Controller
public class ProfileController {
@Autowired
private UserPreferences userPreferences;
@GetMapping("/theme")
public String getTheme() {
return userPreferences.getTheme();
}
}场景说明:用户的主题、语言偏好等需要在会话期间保持。
实际的场景使用
如果后续有使用到,或者有什么不一样的地方,可以单独记录一下。