在 IntelliJ IDEA 中配置 MapStruct 需要进行以下步骤:

  1. 首先需要在 pom.xml 文件中添加 mapstruct 依赖:
<dependency>
    <groupId>org.mapstruct</groupId>
    <artifactId>mapstruct</artifactId>
    <version>1.4.2.Final</version>
</dependency>
  1. 在 IntelliJ IDEA 中安装 MapStruct 插件,可以在 File->Settings->Plugins 中搜索 MapStruct 并安装。

  2. 在项目中创建一个 Mapper 接口,例如:

@Mapper
public interface UserMapper {
    UserDTO toDTO(User user);
    User toEntity(UserDTO userDTO);
}
  1. 在 IDEA 的 Settings 中进行配置,可以在 File->Settings->Build,Execution,Deployment->Compiler->Annotation Processors 中进行配置:
  • 勾选 Enable annotation processing;
  • 在 Annotation processors 字段中添加 org.mapstruct.ap.MappingProcessor。
  1. 重新 build 项目,MapStruct 会自动生成 Mapper 的实现类。

  2. 在代码中使用 Mapper,例如:

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public UserDTO getUserById(Long id) {
        User user = userRepository.findById(id).orElse(null);
        return userMapper.toDTO(user);
    }
}

以上就是在 idea 中配置 map-struct 的步骤。

IntelliJ IDEA 中配置 MapStruct:详细步骤和示例

原文地址: https://www.cveoy.top/t/topic/nSGk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录