【问题标题】:Spring @Scope("token") in component @Component组件 @Component 中的 Spring @Scope("token")
【发布时间】:2018-07-29 05:45:35
【问题描述】:

我有 Angular 5 前端和 Spring 5 REST 后端的应用程序。我需要弹簧组件,女巫为一个令牌创建了一次。如果我一直在使用非 REST API,我可以使用 @Scope("session")。但是现在每个请求的 Session ID 都是不同的。

我需要那个,因为 java.security.Principal in 只提供用户名。但我需要按客户 ID 过滤我的实体。

我不想在每次请求时从数据库中获取客户。

【问题讨论】:

  • 这听起来像是一个糟糕的设计——一般来说,您希望在服务器上设计没有长寿命状态的系统,以最大限度地减少扩展和升级问题。 Java 对象通常很便宜,通常的方法是为每个请求创建一个新的 whatever

标签: java spring rest scope components


【解决方案1】:

创建自己的范围。阅读 spring 文档至use a custom scope,或转到Using custom scope 。你会发现很多例子,

创建一个实现 Scope 接口的 TokenScope 类,并像使用 bean 的任何其他范围一样使用它。

对于典型的 Spring Boot 应用

@Qualifier
@Scope("token")
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface TokenScoped {
}

并使用它。

@Component
@TokenScoped 
class SomeBean

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    相关资源
    最近更新 更多