SpEL(Spring Expression Language)是一种Spring表达式语言,可在JPA数据查询中使用。有时一些查询需要和登录用户上下文关联,比如用户名查询一些信息等等。这里介绍一种通过SpEL在JPA查询中自动关联用户信息的方式。

1 获取登录用户上下文信息

创建自定义类SecurityEvaluationContextExtension用于获取登录用户的信息。完整代码如下:

public class SecurityEvaluationContextExtension implements EvaluationContextExtension {

    @Override
    public String getExtensionId() {
        return "security";
    }

    @Override
    public SecurityExpressionRoot getRootObject() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return new SecurityExpressionRoot(authentication) {
        };
    }
}

Springboot 2.1.0版本之前使用EvaluationContextExtensionSupport来获取上下文信息,之后该类被废弃,直接使用EvaluationContextExtension接口。当前案例Springboot版本为2.2.6,所以使用EvaluationContextExtension接口。

2 创建配置类

创建自定义类SecurityConfiguration,在类中使用上一步创建的SecurityEvaluationContextExtension注册一个Bean,代码如下:

@Configuration
public class SecurityConfiguration {

    @Bean
    EvaluationContextExtension securityExtension() {
        return new SecurityEvaluationContextExtension();
    }
}

3 使用方式

3.1 添加数据库操作

在之前创建的用户操作JPA接口UserRepository中添加两个方法,并指定查询语句,语句中使用SpEL。下面通过nativeQuery非nativeQuery两种语句类型验证SpEL使用。

nativeQuery方式和正常sql语句相同,而非nativeQuery方式在语句中则使用相关表对应的实体和实体字段。更多SpEL写法可参考官方案例

@Repository
public interface UserRepository extends PagingAndSortingRepository<User, Integer>, JpaRepository<User, Integer> {
    Optional<User> findByUsername(String userName);

    int countAllByUsername(String userName);

	//非nativeQuery
    @Query("select u from User u where u.realName = ?#{principal.realName}")
    List<User> findCurrentUserBySpel();

	//nativeQuery
    @Query(value = "select * from h_user u where u.real_name = ?#{principal.realName}", nativeQuery = true)
    List<User> findCurrentUserByNativeQuery();
}

3.2 添加请求处理

在之前的DemoController中,针对上一步的两个方法添加两个请求,代码如下:

@PostMapping("/demo/getUserBySpel")
public HResponse getUserBySpel(Authentication auth) {
    if (auth == null) {
        return HResponse.error("请登录后操作!");
    }
    return HResponse.success(this.userRepository.findCurrentUserBySpel());
}
@PostMapping("/demo/getUserByNativeQuery")
public HResponse getUserByNativeQuery(Authentication auth) {
    if (auth == null) {
        return HResponse.error("请登录后操作!");
    }
    return HResponse.success(this.userRepository.findCurrentUserByNativeQuery());
}

注意:由于SpEL中使用了登录用户的上下文,所以必须登录后才能正常执行,而之前在<<Spring Boot:基于JWT和Spring Security的登录验证>>中已经忽略了/demo/**请求的登录验证,所以在当前请求中需要提前做登录验证处理,否则获取到用户上下文不是用户对象,而是一个anonymousUser字符串

4 请求模拟

先发送登录请求,获取token,然后使用token模拟上一步骤中创建的两个请求,可达到预期效果。

4.1 登录请求

springboot手工加载上下文_后端

4.2 非nativeQuery方式

springboot手工加载上下文_java_02

4.3 nativeQuery方式

springboot手工加载上下文_spring_03

参考

[1] SpEL Query官方介绍 [2] SpEL查询中使用应用上下文信息 [3] 更多SpEL查询官方案例