我的代码在flatmap中给出错误。
public Optional<User> getUserWithAuthorities() {
return SecurityUtils.getCurrentUserLogin().flatMap(UserDao::findOneWithAuthoritiesByLogin);
}
下面是错误:
controller/AuthenticationController.java:[77,51] method flatMap in class java.util.Optional<T> cannot be applied to given types;
[ERROR] required: java.util.function.Function<? super java.lang.String,java.util.Optional<U>>
[ERROR] found: UserDao::f[...]Login
[ERROR] reason: cannot infer type-variable(s) U
[ERROR] (argument mismatch; invalid method reference
[ERROR] cannot find symbol
[ERROR] symbol: method findOneWithAuthoritiesByLogin(java.lang.String)
[ERROR] location: interface net.javaguides.springboot.dao.UserDao)
UserDao代码:
@Repository
public interface UserDao extends JpaRepository<User, Long> {
User findByUsername(String username);
Optional<User> findOneWithAuthoritiesByLogin(String login);
}
这是securitytils的代码:
public final class SecurityUtils {
private SecurityUtils() {}
/**
* Get the login of the current user.
*
* @return the login of the current user.
*/
public static Optional<String> getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication()));
}
private static String extractPrincipal(Authentication authentication) {
if (authentication == null) {
return null;
} else if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
return springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
return (String) authentication.getPrincipal();
}
return null;
}
有什么问题吗?
引用接口类UserDao::findOneWithAuthoritiesByLogin
导致错误。Java不能单独使用接口调用该方法。
要解决这个问题,可以引用UserDao
类型的实例化对象。
下面是接口的一个示例实现:
class UserDaoImplementation implements UserDao {
@Override
public Optional<User> findOneWithAuthoritiesByLogin(String login) {
User user = User.builder().name("Tom").build();
return Optional.of(user);
}
}
然后创建一个实例并引用它而不是接口类:
public static Optional<User> getUserWithAuthorities() {
UserDao userDao = new UserDaoImplementation();
return SecurityUtils.getCurrentUserLogin().flatMap(userDao::findOneWithAuthoritiesByLogin);
}
在这种情况下,getUserWithAuthorities
方法现在返回一个包含User
对象的Optional
。