找不到类的主构造函数或单个唯一构造函数- spring Boot

xam8gpfp  于 2023-04-10  发布在  Spring
关注(0)|答案(2)|浏览(236)

我在使用Spring 2.7.4 时遇到了这个错误:未找到类com.library.project.library_el_aleph.model.Client的主构造函数或唯一构造函数我在POJO实体类中有两个构造函数用于两个可能的插入

@Repository
 public interface RoleRespository extends CrudRepository<Role, Integer>{

     Role findByUserName(RoleList roleName);

public Cliente(@NotEmpty @Pattern(regexp = "^[A-Z][a-zA-Z]+") String userName, 
@NotEmpty String email,
    @NotEmpty String contraseña) {
    this.userName = userName;
    this.email = email;
    this.contraseña = contraseña;
}

public Cliente(String productosCliente,
    @NotEmpty @Pattern(regexp = "^[A-Z][a-zA-Z]+") String userName, @NotEmpty String segundoNombre,
    @NotEmpty String primerApellido, @NotEmpty String segundoApellido, @NotEmpty String ciudadCliente,
    @NotEmpty String direccionCliente, @NotEmpty String email, @NotEmpty String contraseña,
    @NotNull @Past Date fechaNacimiento, @NotNull Set<Role> roles) {
    
    this.productosCliente = productosCliente;
    this.userName = userName;
    this.segundoNombre = segundoNombre;
    this.primerApellido = primerApellido;
    this.segundoApellido = segundoApellido;
    this.ciudadCliente = ciudadCliente;
    this.direccionCliente = direccionCliente;
    this.email = email;
    this.contraseña = contraseña;
    this.fechaNacimiento = fechaNacimiento;
    this.roles = roles;
}

}

这是我的RESTController的代码的一部分,其中包含设置@ RequestBody输入的方法:

@RequestMapping(value= "/register", method = RequestMethod.POST)
public ResponseEntity<Object> register(@Valid @RequestBody NewUser newUser, 
BindingResult send){
    
    if(send.hasErrors())
        return new ResponseEntity<>(new Message("Error en el registro, por favor 
    valide nuevamente"), HttpStatus.BAD_REQUEST);

    try {
        Cliente creatingUser = new Cliente(newUser.getPrimerNombre(), 
        newUser.getEmail(), passwordEncoder.encode(newUser.getPassword()));
        Set<Role> roles = new HashSet<>();
        roles.add(roleServices.getRoleByName(RoleList.ROLE_USER).get());
        if(newUser.getRoles().contains("Admin"))
            roles.add(roleServices.getRoleByName(RoleList.ROLE_ADMIN).get());
        creatingUser.setRoles(roles);
        clienteServices.saveNewUser(creatingUser);
        return new ResponseEntity<>(new Message("El usuario ha sido creado correctamente"), HttpStatus.OK);

    } catch (Exception e) {
        return new ResponseEntity<Object>(new Message("Ha ocurrido un error inesperado con el servidor, por favor intente nuevamente más tarde"), HttpStatus.BAD_REQUEST);
        
    }  
}

这是我第一次为同一个类使用多个构造函数,我想这就是为什么这个错误是由于...有人能帮助我吗?

wswtfjt7

wswtfjt71#

重写构造函数时,必须包含默认构造函数.
“我们还必须注意到,当我们在类中没有使用任何构造函数时,java编译器会调用默认构造函数。但是,如果我们在类中使用了任何构造函数,无论是默认构造函数还是参数化构造函数,则不会调用默认构造函数。在这种情况下,java编译器会抛出一个异常,说明该构造函数未定义。”
解决方案:使用Lombok @NoArgsConstructor或
public void run(){
}
https://www.javatpoint.com/constructor-overloading-in-java

xv8emn3q

xv8emn3q2#

我也遇到过类似的问题,但还没能找到解决办法

相关问题