You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot启动失败:缺少org.modelmapper.ModelMapper类型Bean

问题原因

Spring Boot启动失败是因为ProgrammingLanguageManager的构造函数需要org.modelmapper.ModelMapper类型的Bean,但Spring容器中没有定义该Bean,导致依赖注入无法完成。

解决方案

需要完成两个步骤:确保引入ModelMapper依赖,然后在Spring配置中注册ModelMapper Bean。

1. 确认ModelMapper依赖已引入

Maven项目(修改pom.xml)

<dependency>
    <groupId>org.modelmapper</groupId>
    <artifactId>modelmapper</artifactId>
    <version>3.1.1</version> <!-- 可替换为最新稳定版本 -->
</dependency>

Gradle项目(修改build.gradle)

implementation 'org.modelmapper:modelmapper:3.1.1'

2. 注册ModelMapper Bean

有两种简单的方式可以实现:

方式一:创建独立配置类

新建一个配置类,专门负责ModelMapper的Bean注册:

import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ModelMapperConfig {
    
    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        // 可选:添加自定义配置,比如严格匹配策略
        // modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        return modelMapper;
    }
}

方式二:在启动类中直接注册

如果不想新建配置类,也可以直接在Spring Boot启动类中添加Bean定义:

import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class YourApplication {

    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }

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

额外优化建议

Spring 4.3+版本支持构造函数自动注入,你可以省略@Autowired注解,让代码更简洁:

@Service
public class ProgrammingLanguageManager implements ProgrammingLanguageService {

    private final ProgrammingLanguageRepository programmingLanguageRepository;
    private final ModelMapper modelMapper;

    // 无需@Autowired,Spring会自动注入构造函数参数
    public ProgrammingLanguageManager(ProgrammingLanguageRepository programmingLanguageRepository,
            ModelMapper modelMapper) {
        this.programmingLanguageRepository = programmingLanguageRepository;
        this.modelMapper = modelMapper;
    }

    // 其他业务方法...
}

内容的提问来源于stack exchange,提问作者Fatih Selvi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:50:23