【wiki知识库】08.添加用户登录功能--后端SpringBoot部分
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.wikibook.core.dao.UserRepository;
import com.wikibook.core.entity.User;
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
return user;
}
}
这段代码实现了UserDetailsService
接口,用于加载用户信息。当用户尝试登录时,Spring Security会调用loadUserByUsername
方法来获取用户信息。如果用户不存在,则抛出UsernameNotFoundException
异常。这个服务类注入了UserRepository
,用于查询数据库中的用户信息。
评论已关闭