Java / MapStruct Java Interview questions part 2
How do you use MapStruct with Spring Boot?
Set componentModel = "spring" on the mapper, and MapStruct generates the implementation as a Spring-managed bean annotated with @Component. You can then autowire the mapper interface anywhere in the application context.
@Mapper(componentModel = "spring") public interface UserMapper { UserDto toDto(User user); } @Service public class UserService { private final UserMapper userMapper; public UserService(UserMapper userMapper) { this.userMapper = userMapper; } }
No separate configuration class or bean method is needed; Spring's component scan finds the generated UserMapperImpl automatically because it lives in a scanned package.
More Related questions...