spring 使用MapStruct的Sping Boot 问题

k5ifujac  于 2024-01-05  发布在  Spring
关注(0)|答案(3)|浏览(135)

我是新来的Spring Boot 。我希望有人能帮助我了解我做错了什么。
我创造了服务。

  1. @RequiredArgsConstructor
  2. @Service
  3. public class UserService {
  4. private final UserRepository userRepository;
  5. private final UserMapper userMapper;
  6. public UserDto login(CredentialDto credentialDto) {
  7. User user = userRepository.findBylogin(credentialDto.login())
  8. .orElseThrow(()-> {
  9. ApplicationException ex =new ApplicationException();
  10. ex.setMessage("Unknown user");
  11. return ex;
  12. });
  13. return userMapper.toUserDto(user);
  14. }
  15. }

字符串
我的Mapper类是:

  1. @Mapper(componentModel = "spring")
  2. public interface UserMapper {
  3. UserDto toUserDto(User user);
  4. }


我在IDE中得到错误,如下所示:

说明:

  1. Parameter 1 of constructor in com.example.jwttest.service.UserService required a bean of type 'com.example.jwttest.mappers.UserMapper' that could not be found.

操作:

  1. Consider defining a bean of type 'com.example.jwttest.mappers.UserMapper' in your configuration.


非常感谢任何帮助。

vhmi4jdf

vhmi4jdf1#

可能你没有配置好:
除了依赖:

  1. <dependency>
  2. <groupId>org.mapstruct</groupId>
  3. <artifactId>mapstruct</artifactId>
  4. <version>${org.mapstruct.version}</version>
  5. </dependency>

字符串
你还需要配置maven-compiler-plugin

  1. <plugin>
  2. <groupId>org.apache.maven.plugins</groupId>
  3. <artifactId>maven-compiler-plugin</artifactId>
  4. <version>3.8.0</version>
  5. <configuration>
  6. <annotationProcessorPaths>
  7. <path>
  8. <groupId>org.mapstruct</groupId>
  9. <artifactId>mapstruct-processor</artifactId>
  10. <version>${org.mapstruct.version}</version>
  11. </path>
  12. <path>
  13. <groupId>org.projectlombok</groupId>
  14. <artifactId>lombok</artifactId>
  15. <version>${lombok.version}</version>
  16. </path>
  17. <dependency>
  18. <groupId>org.projectlombok</groupId>
  19. <artifactId>lombok-mapstruct-binding</artifactId>
  20. <version>0.2.0</version>
  21. </dependency>
  22. </annotationProcessorPaths>
  23. <compilerArgs>
  24. <compilerArg>
  25. -Amapstruct.defaultComponentModel=spring
  26. </compilerArg>
  27. </compilerArgs>
  28. </configuration>
  29. </plugin>


查看此分步教程:springframework.guru/mapstruct

展开查看全部
chy5wohz

chy5wohz2#

你可以看看我在GitHub上的迷你项目,它演示了MapStruct与Spring https://github.com/youssefehaab/java-mapstruct/tree/v1.0.0的集成。

kr98yfug

kr98yfug3#

如果你使用maven,也许你可以尝试先使用mvn clean命令进行清理。

相关问题