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 登录请求
4.2 非nativeQuery方式
4.3 nativeQuery方式
参考
[1] SpEL Query官方介绍 [2] SpEL查询中使用应用上下文信息 [3] 更多SpEL查询官方案例