ModelMapper in Spring Boot No Starter

Using ModelMapper in Spring Boot without the Starter

I’ve written a handful of posts about using ModelMapper in Spring Boot applications.  When I’m working on something, I generally try to use the newest, stable version.  It recently dawned on me that the version for the Model Mapper starter was never changing.

I investigated some more and found that it’s been sitting at version 1.1.0 since December 2015.  It brings in modelmapper-0.7.5.jar.  At the time of this writing, ModelMapper itself is at 2.3.0.

So in this quick post, I’m going to go over how to use ModelMapper in your Spring Boot application without using the starter.

Gradle Dependency

implementation('org.modelmapper:modelmapper:2.3.0')

The Controller

When we use the starter, we just add a Gradle dependency and then autowire the ModelMapper instance in our controllers.

@Controller
public class TaskController {
   @Autowired
   private TaskRepository taskRepository;
   @Autowired
   private ModelMapper modelMapper;

   ...
}

If we do that and try to start our application using bootRun, it won’t start and we’ll see the following error message.

***************************
APPLICATION FAILED TO START
***************************

Description:

Field modelMapper in com.amydegregorio.modelmappernostarter.controller.TaskController required a bean of type 'org.modelmapper.ModelMapper' 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 'org.modelmapper.ModelMapper' in your configuration.


> Task :bootRun FAILED

We get this message because the primary thing the starter did for us was define the ModelMapper bean.  Now, we need to do that for ourselves.

Defining the Bean

In order to define the ModelMapper bean, we’re going to use Spring’s @Configuration and @Bean annotations.  Annotating a class as Configuration tells Spring that you’ll be declaring Beans in it.  Our bean method just creates a ModelMapper instance and returns it, but if you wanted to override some of it’s configuration and have it apply globally, this is the place to do it.

With this configuration in place, our application will start up and run as expected.

@Configuration
public class ApplicationConfig {

   @Bean
   public ModelMapper modelMapper() {
      ModelMapper modelMapper = new ModelMapper();
      return modelMapper;
   }
}

Conclusion

In this post, we’ve seen how to configure our own ModelMapper bean, so that we can use the latest version of ModelMapper without relying on Starters which might not be maintained.

The example code is available over on GitHub.

13 thoughts on “ModelMapper in Spring Boot No Starter

Leave a comment