springboot+构造函数

yrdbyhpb  于 2021-06-29  发布在  Java
关注(0)|答案(3)|浏览(353)

它一直给我那个错误,我不知道如何集中在问题上或在哪里搜索它一直问我关于构造函数,但我使用Lombok山,所以我为什么要做构造函数,我真的不知道是什么问题的代码。
以下是用户型号代码:

package com.muskiltak.v1.model;

import lombok.*;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "users")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
public class User {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Column(name = "username")
private String username;

@Column(name = "email")
private String email;

@Column(name = "phone")
private Integer phone;

@Column(name = "password")
private String password;

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable( name = "user_roles",
        joinColumns = @JoinColumn(name = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
}

,这是下面的榜样代码:

package com.muskiltak.v1.model;

import com.muskiltak.v1.utility.enums.Roles;
import lombok.*;

import javax.persistence.*;

@Entity
@Table(name = "roles")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
public class Role {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Enumerated(EnumType.STRING)
@Column(name = "name")
private Roles name;
}

这是authcontroller代码:

package com.muskiltak.v1.controller;

import com.muskiltak.v1.utility.enums.Roles;
import com.muskiltak.v1.model.Role;
import com.muskiltak.v1.model.User;
import com.muskiltak.v1.repository.RoleRepo;
import com.muskiltak.v1.repository.UserRepo;
import com.muskiltak.v1.service.UserDetailsImpl;
import com.muskiltak.v1.utility.JWT.JwtUtils;
import com.muskiltak.v1.utility.payload.request.LoginRequest;
import com.muskiltak.v1.utility.payload.request.RegisterRequest;
import com.muskiltak.v1.utility.payload.response.JwtResponse;
import com.muskiltak.v1.utility.payload.response.MessageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/v1")
public class AuthController {

@Autowired
AuthenticationManager authenticationManager;

@Autowired
UserRepo userRepository;

@Autowired
RoleRepo roleRepository;

@Autowired
PasswordEncoder encoder;

@Autowired
JwtUtils jwtUtils;

@PostMapping("/login")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {

    Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

    SecurityContextHolder.getContext().setAuthentication(authentication);
    String jwt = jwtUtils.generateJwtToken(authentication);

    UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
    List<String> roles = userDetails.getAuthorities().stream()
            .map(GrantedAuthority::getAuthority)
            .collect(Collectors.toList());

    return ResponseEntity.ok(new JwtResponse(jwt,
            userDetails.getId(),
            userDetails.getUsername(),
            userDetails.getEmail(),
            userDetails.getPhone(),
            roles));
}

@PostMapping("/register")
public ResponseEntity<?> registerUser(@Valid @RequestBody RegisterRequest registerRequest) {
    if (userRepository.existsByUsername(registerRequest.getUsername())) {
        return ResponseEntity
                .badRequest()
                .body(new MessageResponse("Error: Username is already taken!"));
    }

    if (userRepository.existsByEmail(registerRequest.getEmail())) {
        return ResponseEntity
                .badRequest()
                .body(new MessageResponse("Error: Email is already in use!"));
    }

    if (userRepository.existsByPhone(registerRequest.getPhone())) {
        return ResponseEntity
                .badRequest()
                .body(new MessageResponse("Error: Phone Number is already in use!"));
    }

    // Create new user's account
    User user = new User(
            registerRequest.getUsername(),
            registerRequest.getEmail(),
            registerRequest.getPhone(),
            encoder.encode(
                    registerRequest.getPassword()
            )
    );

    Set<String> strRoles = registerRequest.getRole();
    Set<Role> roles = new HashSet<>();

    if (strRoles == null) {
        Role userRole = roleRepository.findByName(Roles.USER)
                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
        roles.add(userRole);
    } else {
        strRoles.forEach(role -> {
            switch (role) {
                case "admin":
                    Role adminRole = roleRepository.findByName(Roles.ADMIN)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(adminRole);

                    break;
                case "moderator":
                    Role moderatorRole = roleRepository.findByName(Roles.MODERATOR)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(moderatorRole);

                    break;
                case "corp":
                    Role corpRole = roleRepository.findByName(Roles.CORP)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(corpRole);

                    break;
                default:
                    Role userRole = roleRepository.findByName(Roles.USER)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(userRole);
            }
        });
    }

    user.setRoles(roles);
    userRepository.save(user);

    return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
}
}

一直给我相同的错误,你可以在下面的图片中看到,即使我运行它与调试模式,它一直要求我使构造函数,我使用lombok,你可以看到

n7taea2i

n7taea2i1#

你正在使用 Lombok :一个不接受参数,另一个将所有字段都作为参数。您正在调用一个不存在的构造函数,它只接受 User .
替换此:

// Create new user's account
User user = new User(
        registerRequest.getUsername(),
        registerRequest.getEmail(),
        registerRequest.getPhone(),
        encoder.encode(
            registerRequest.getPassword()
        )
);

与下面的代码应该工作。

// Create new user's account
User user = new User();
user.setUsername(registerRequest.getUsername());
user.setEmail(registerRequest.getEmail());
user.setPhone(registerRequest.getPhone());
user.setPassword(encoder.encode(registerRequest.getPassword()));

或者,您可以手动将具有这4个参数的构造函数添加到 User 班级。

cmssoen2

cmssoen22#

根据lombok,将要创建的构造函数的所有属性类型的顺序都与所定义的相同。因此,@allargsconstructor注解将创建一个如下所示的构造函数:

public User(long id, String username, Integer phone, String password, HashSet<Role> roles);

在第94行中,您试图为一个需要6的构造函数提供4个值。您可以通过以下可能的方法解决问题:
在authcontroller的第94行中为id传递一些默认值,为roles传递null。
只需要四个参数就可以编写构造函数。
删除@allargsconstructor注解,只创建所需的构造函数,而不提供全参数构造函数。

stszievb

stszievb3#

您使用的构造函数既不是无参数构造函数,也不是接收所有参数的构造函数。将用户名、电子邮件、电话和密码传递给构造函数。这是你的四个领域 User 类,但该类具有更多字段,因此构造函数与lombok生成的任何构造函数都不匹配。必须显式地编写该构造函数,或者传递适当的参数,以便它与lombok生成的构造函数之一匹配。

相关问题