我不知道我的Spring Boot应用程序发生了什么,但是现在由于错误而无法启动它:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userConverter in webapp.controllers.UserResourceController required a bean of type 'webapp.converter.UserConverter' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'webapp.converter.UserConverter' in your configuration.
Process finished with exit code 1
控制器代码:
@RestController
@RequestMapping("/api/user")
public class UserResourceController {
@Autowired
private UserServiceImpl userService;
@Autowired
private UserConverter userConverter;
@PostMapping
public ResponseEntity<UserDto> addUser(@RequestBody UserDto userDto) {
userService.persist(userConverter.toUser(userDto));
return ResponseEntity.ok().body(userDto);
}
@GetMapping
public ResponseEntity<List<UserDto>> findAllUsers() {
return ResponseEntity.ok(userConverter.toUserDtos(userService.getAll()));
}
@PutMapping("/api/user/{id}")
public ResponseEntity<UserDto> updateUser(@PathVariable Long id, @RequestBody UserDto userDto) {
User user = userConverter.toUser(userDto);
user.setId(id);
userService.persist(user);
return ResponseEntity.ok().body(userDto);
}
@GetMapping("/api/user/{id}")
public ResponseEntity<UserDto> findUser (@PathVariable Long id) {
Optional<User> user = Optional.ofNullable(userService.getByKey(id));
return ResponseEntity.ok(userConverter.toUserDto(user.get()));
}
}
映射器类:
@Mapper(componentModel = "spring")
@Service
public abstract class UserConverter {
public abstract User toUser(UserDto userDto);
public abstract UserDto toUserDto(User user);
public abstract List<UserDto> toUserDtos(List<User> users);
}
首先,我尝试在没有@Service
批注的情况下运行它,然后尝试使用它批注,但是我总是看到相同的错误。
答案 0 :(得分:0)
您不能注入没有任何实际实现的抽象类。即使没有Spring,在Java中也是不可能的。那么,您是否期望它可以被注入?
我不明白您为什么需要注入该课程。最好的解决方案是使用适当的转换器创建实用程序类,例如:
public final class UserConverter {
private UserConverter() {}
public static UserDTO toUserDTO(User employee) {
Department empDp = employee.getDepartment();
return UserDTO.builder()
.id(employee.getId())
.name(employee.getName())
.active(employee.getActive())
.departmentId(empDp.getId())
.departmentName(empDp.getName())
.build();
}
public static User toUser(UserDTO dto) {
Department dp = Department.builder()
.id(dto.getDepartmentId())
.name(dto.getDepartmentName())
.build();
return User.builder()
.id(dto.getId())
.name(dto.getName())
.active(dto.getActive())
.department(dp)
.build();
}
}
并从您的代码中将其作为静态方法调用:
@GetMapping("/{id}")
public ResponseEntity<UserDto> findUser (@PathVariable Long id) {
return userService.getByKey(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
此外,您的代码在API方面存在一些错误:
@RequestMapping("/api/users")
->并且仅当您需要通过id进行操作时,添加@GetMapping("/{id}")
201 - Create
状态代码,而不是 200 如果/api
对于所有API应该是通用的,则可以在配置文件中为所有资源定义它。
applicatoin.yml
的摘要:
服务器: Servlet: 上下文路径:/ api
有关MapStruct解决方案的有用参考: