在启动spring应用程序期间无法注入mapstruct接口

问题描述

我有以下映射器(mapstruct版本1.3.1最终版)。

@Mapper(componentModel = "spring",uses = {},unmappedTargetPolicy = ReportingPolicy.WARN)
public interface AccountMapper {
    @Mapping(source = "registrationDto.email",target = "email")
    @Mapping(source = "passwordDto.hashPassword",target = "password")
    Account from(RegistrationDto registrationDto,PasswordDto passwordDto);
}

当我尝试运行spring应用程序时,我发现找不到与Mapper关联的bean。

Parameter 1 of constructor in com.xx.xx.Controller required a bean of type 'com.xxx.AccountMapper' that Could not be found.

Consider defining a bean of type 'com.xxx.AccountMapper' in your configuration.

我尝试了用装饰器解决。通过为界面添加注释@DecoratedWith(AccountMapperDecorator.class)并创建以下类。

@Component
public abstract class AccountMapperDecorator implements AccountMapper {

    @Autowired
    @Qualifier("delegate")
    private AccountMapper delegate;

    @Override
    public Account from(RegistrationDto registrationDto,PasswordDto passwordDto) {
        return delegate.from(registrationDto,passwordDto);
    }
}

然后我收到。

No qualifying bean of type 'com.xxx.AccountMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true),@org.springframework.beans.factory.annotation.Qualifier(value="delegate")}

在那种情况下可能是什么问题?

解决方法

您是否运行过mvn package? 在IDE中搜索类AccountMapperImpl时,可以找到它吗?如果不是这样,那就是一个问题。如果找不到,Spring也不会。

也许您忘记在pom.xml中配置(或配置错误)mapstruct-processor?你有类似的东西吗?

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.5.1</version>
    <configuration>
        <source>1.8</source>
        <target>1.8</target>
        <annotationProcessorPaths>
            <path>
                <groupId>org.mapstruct</groupId>
                <artifactId>mapstruct-processor</artifactId>
                <version>...</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>

有吗?

,

这种情况不时发生,
如果您会注意到,那么可能不会在db.php文件夹中生成AccountMapperImpl 有几种方法可以解决此问题:

  • 尝试清理target/build目录
  • 运行out/buildmvn clean compile
  • 设置您的IDE以使用gradle clean compileJava运行代码 enter image description here
  • 确保已启用maven/gradle