猿问

如何实例化 java.security.Principal?所有子类都已弃用

我有一个接受 Principal 的 Spring API 服务。


public ResponseEntity<ApiCustomResponse> create(Principal principal, UrlInfoData urlinfo) throws ApiException;

Principal 由 Spring 自动为 OAuth2 API 调用创建。我想为网页管理界面使用相同的服务。


@Autowired

private IShortUrlService apiService;

...

    Principal principal = new Principal();

    apiService.create(principal, urlinfo);

我想用当前登录的管理员用户名实例化委托人。但是,所有实例化类都已弃用。如何实例化 Principal 以传递给服务?


https://docs.oracle.com/javase/8/docs/api/java/security/Principal.html


翻过高山走不出你
浏览 172回答 1
1回答

MMMHUHU

既然java.security.Principal是接口,为什么不实现呢?Principal principal = new Principal() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public String getName() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return adminName;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }apiService.create(principal, urlinfo);此外,您可以通过以下方式获取当前登录用户的 Principal:SecurityContextHolder.getContext().getAuthentication().getPrincipal()
随时随地看视频慕课网APP

相关分类

Java
我要回答