首页 > 解决方案 > SpringBoot + Gradle + Mapstruct 失败,在运行时找不到 bean

问题描述

我知道这是重复的问题,但看起来配置错误。抱歉重复类似的问题。

我的 build.gradle 是

/* ========================
 * Build
 * ========================
 */
buildscript {
    ext {
        springBootVersion = '2.4.4.RELEASE'
    }
    repositories {
        mavenCentral()
        maven {
              url "https://plugins.gradle.org/m2/"
        }
        jcenter()
        
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.4.4")
        classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.5"
        classpath "io.spring.gradle:dependency-management-plugin:0.6.1.RELEASE"
    }
}

/* ========================
 * Plugins
 * ========================
 */
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'jacoco'
apply plugin: "org.ajoberstar.grgit"
apply plugin: 'java-library'

/* ========================
 * Project Info
 * ========================
 */
version = '1.0.0'

sourceCompatibility = 11
targetCompatibility = 11

defaultTasks 'bootRun'

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}


/* ========================
 * Dependencies
 * =========================
 */
repositories {
    mavenCentral()
    
}

configurations {
    providedRuntime
}

ext {
    mapstructVersion = "1.0.0.Beta4"
    lombokVersion = "1.18.10"
    generatedMapperSourcesDir = "${buildDir}/generated-src/mapstruct/main"
}

dependencies {



    compileOnly "org.projectlombok:lombok:${lombokVersion}"
    annotationProcessor "org.projectlombok:lombok:${lombokVersion}"

    implementation "org.mapstruct:mapstruct:1.4.2.Final"
    annotationProcessor "org.mapstruct:mapstruct-processor:1.4.2.Final"
    implementation "org.mapstruct:mapstruct-processor:1.4.2.Final"


    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.integration:spring-integration-test'
    implementation 'org.springframework.cloud:spring-cloud-starter-openfeign:3.0.3'
    implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.13'

    implementation 'org.springframework.boot:spring-boot-starter-actuator:2.5.3'

    implementation 'org.springframework.cloud:spring-cloud-netflix-ribbon:2.0.0.RELEASE'
    implementation 'org.springframework.cloud:spring-cloud-openfeign-core:3.0.3'
    implementation group: 'org.springframework.integration', name: 'spring-integration-webflux', version: '5.5.3'
    implementation group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.12.4'
    implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.12.4'

    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
    implementation fileTree(include: ['*.jar'], dir: 'libs')
}

我的 MapstructMapper 是

import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Mappings;
import org.mapstruct.ReportingPolicy;


@Mapper(componentModel = "spring")
public interface TestTransformer {

    @Mappings({
          @Mapping(target="lastName", source="resp.name"),
          @Mapping(target="statusCode", source="resp.status")
        })
    AResponse toResponseA(BResponse resp);
}

我的豆子是

import java.io.Serializable;
//
//import lombok.Data;
//import lombok.EqualsAndHashCode;
//import lombok.ToString;

//@EqualsAndHashCode(callSuper=false)
//@ToString
//@Data
public class AResponse implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String name;
    private String number;
    private String status;
    private String phoneNumber;

    //Manually added setters & getters
    
}

--------------------


//import lombok.Data;
//import lombok.ToString;

//@ToString
//@Data
public class BResponse {
    private String customerID        ;
    private String prefix            ;
    private String firstName         ;
    private String middleName        ;
    private String lastName          ;
    private String suffix            ;
    private String gender            ;
    private String statusCode        ;
    private String phoneID           ;
    private String phoneNumber       ;
    private String abltecID          ;
    private String abltecBPIndicator ;
    private String ebIndicator       ;
    private String update         ;
    private Address address;

    //Manually added setters & getters
}


我的实现是

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.mapstruct.factory.Mappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ServiceImpl implements Service {
    
    @Autowired
    private ServiceGateway client;
    
    BResponse[] arr;
    
    private TestTransformer tf = Mappers.getMapper(TestTransformer.class);//

    //@Autowired
    //private TestTransformer tf;//Autowiring failed

    @Override
    public Object info(String num) {
        ResponseEntity<Object> response = client.search(num);//This is my Feign client
        
        arr = CommonUtils.convertJSONToObject(response.getBody(), BResponse[].class);//This is converting the response body into Array working perfect !
        
        List<AResponse> output = Arrays.asList(arr).stream().map(m -> tf.toResponseA(m)).collect(Collectors.toList());
        System.out.println("Total Size : "+output.size());
        
        return output;
    }
}

我的环境 Java:JDK-11

gradle clean build 命令正常工作,并且还生成了 MapperImpl 在此处输入图像描述

但是当我启动应用程序时,我收到了这个错误


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

[0;39m No active profile set, falling back to default profiles: default
[0;39m BeanFactory id=d4a9481e-cd19-390f-9e68-9dc4408ce16d
[0;39m No bean named 'errorChannel' has been explicitly defined. Therefore, a default PublishSubscribeChannel will be created.
[0;39m No bean named 'integrationHeaderChannelRegistry' has been explicitly defined. Therefore, a default DefaultHeaderChannelRegistry will be created.
[0;39m Bean 'integrationChannelResolver' of type [org.springframework.integration.support.channel.BeanFactoryChannelResolver] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[0;39m Bean 'integrationDisposableAutoCreatedBeans' of type [org.springframework.integration.config.annotation.Disposables] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[0;39m Bean 'org.springframework.integration.config.IntegrationManagementConfiguration' of type [org.springframework.integration.config.IntegrationManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[0;39m Tomcat initialized with port(s): 8080 (http)
[0;39m Starting service [Tomcat]
[0;39m Starting Servlet engine: [Apache Tomcat/9.0.50]
[0;39m Initializing Spring embedded WebApplicationContext
[0;39m Root WebApplicationContext: initialization completed in 2100 ms
[0;39m Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'serviceController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serviceImpl' defined in file [C:\Users\<removed the package name>\service\ServiceImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [<removed the package name>.service.ServiceImpl]: Constructor threw exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: Cannot find implementation for <removed the package name>.TestTransformer
[0;39m Stopping service [Tomcat]
[0;39m 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
[2m2021-08-27 15:47:49.314[0;39m [31mERROR[0;39m [35m25164[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.s.boot.SpringApplication              [0;39m [2m:[0;39m Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'serviceController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serviceImpl' defined in file [C:\Users\<removed the package name>\service\ServiceImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [<removed the package name>.service.ServiceImpl]: Constructor threw exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: Cannot find implementation for <removed the package name>.transformer.TestTransformer
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:660) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1413) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.9.jar:5.3.9]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.9.jar:5.3.9]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.5.3.jar:2.5.3]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.5.3.jar:2.5.3]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) ~[spring-boot-2.5.3.jar:2.5.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) ~[spring-boot-2.5.3.jar:2.5.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.3.jar:2.5.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.3.jar:2.5.3]
    at <removed the package name>.MyApp.main(MyApp.java:14) ~[main/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serviceImpl' defined in file [C:\Users\<removed the package name>\service\ServiceImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [<removed the package name>.service.ServiceImpl]: Constructor threw exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: Cannot find implementation for <removed the package name>.transformer.TestTransformer
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1316) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:657) ~[spring-beans-5.3.9.jar:5.3.9]
    ... 20 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [<removed the package name>.service.ServiceImpl]: Constructor threw exception; nested exception is java.lang.RuntimeException: java.lang.ClassNotFoundException: Cannot find implementation for <removed the package name>.transformer.TestTransformer
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:221) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1308) ~[spring-beans-5.3.9.jar:5.3.9]
    ... 31 common frames omitted
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: Cannot find implementation for <removed the package name>.transformer.TestTransformer
    at org.mapstruct.factory.Mappers.getMapper(Mappers.java:61) ~[mapstruct-1.4.2.Final.jar:na]
    at <removed the package name>.service.ServiceImpl.<init>(ServiceImpl.java:29) ~[main/:na]
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) ~[na:na]
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:208) ~[spring-beans-5.3.9.jar:5.3.9]
    ... 33 common frames omitted
Caused by: java.lang.ClassNotFoundException: Cannot find implementation for <removed the package name>.transformer.TestTransformer
    at org.mapstruct.factory.Mappers.getMapper(Mappers.java:75) ~[mapstruct-1.4.2.Final.jar:na]
    at org.mapstruct.factory.Mappers.getMapper(Mappers.java:58) ~[mapstruct-1.4.2.Final.jar:na]
    ... 39 common frames omitted


我的问题是

private TestTransformer tf = Mappers.getMapper(TestTransformer.class);

@Autowired
private TestTransformer tf;//Autowiring failed

以上两种方式都失败了

我没有得到这里失败的地方我尝试使用 Autowire 或从工厂获取但仍然失败

标签: spring-bootmapstruct

解决方案


推荐阅读