简体   繁体   中英

Error creating MapStruct bean with Spring

Trying to do some tests with MapStruct here. I have the following classes:

Test Class

RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MapperTests {

@Autowired
private UsuarioMapper usuarioMapper; //Can't autowire(No typo found)

@Test
public void dadoUsuarioSalvarDTO_quandoMapeioParaUsuario_entaoRetornaUsuario(){

    //Dado
    UsuarioSalvarDTO usuarioSalvarDTO = new UsuarioSalvarDTO();
    usuarioSalvarDTO.setEmail("test@test.com");
    usuarioSalvarDTO.setSenha("123456789");
    usuarioSalvarDTO.setStatus(TipoStatus.ATIVO);

    Usuario usuario = usuarioMapper.toEntity(usuarioSalvarDTO);

    Assert.assertEquals(usuario.getEmail(), "test@test.com");
    Assert.assertEquals(usuario.getSenha(), "123456789");
    Assert.assertEquals(usuario.getStatus(), TipoStatus.ATIVO);


}
}

Mapper

@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.WARN)
public interface UsuarioMapper {

@Mappings({
        @Mapping(target = "id", ignore = true),
        @Mapping(target = "createdAt", ignore = true),
        @Mapping(target = "updatetAt", ignore = true),
        @Mapping(source="usuarioSalvarDTO.email", target = "email")
})
Usuario toEntity(UsuarioSalvarDTO usuarioSalvarDTO);

}

Consider Models here

Generated UsuarioMapperImpl:

@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2018-11-24T00:40:25-0200",
comments = "version: 1.2.0.Final, compiler: javac, environment: Java 1.8.0_181 (Oracle Corporation)"
)
@Component
public class UsuarioMapperImpl implements UsuarioMapper {

@Override
public Usuario toEntity(UsuarioSalvarDTO usuarioSalvarDTO) {
    if ( usuarioSalvarDTO == null ) {
        return null;
    }

    Usuario usuario = new Usuario();

    usuario.setEmail( usuarioSalvarDTO.getEmail() );
    usuario.setSenha( usuarioSalvarDTO.getSenha() );
    usuario.setStatus( usuarioSalvarDTO.getStatus() );

    return usuario;
    }
}

When i try to run the test, he gives the following error:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error         creating bean with name 'br.com.financeiroAdam.demo.MapperTests': Unsatisfied dependency expressed through field 'usuarioMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'br.com.financeiroAdam.demo.mapper.UsuarioMapper' available: expected at least 1 bean which qualifies as autowire candidate.

@Autowire in MapperTest don't work. It claims: 'Could not autowire. No beans of 'UsuarioMapper' type found.'

Already tried:

  • gradle build (no errors)
  • gradle build -x test (no errors)
  • Invalidate Caches / Restart
  • Re-import project

Using:

  • IntelliJ
  • Gradle
  • Spring
  • Lombok

build.gradle

buildscript {
ext {
    springBootVersion = '2.1.0.RELEASE'
}
repositories {
    mavenCentral()
}
dependencies {
    classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}

plugins {
id 'net.ltgt.apt' version '0.8'
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'br.com.financeiroAdam'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
mavenCentral()
}


dependencies {
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
implementation('org.springframework.boot:spring-boot-starter-web')

compileOnly('org.projectlombok:lombok:1.18.2')

compile 'org.mapstruct:mapstruct-jdk8:1.2.0.Final'
testImplementation('org.springframework.boot:spring-boot-starter-test')

apt('org.projectlombok:lombok:1.18.2')
apt('org.mapstruct:mapstruct-processor:1.2.0.Final')

}

Tried everything. I think the mapstruct simply does not want to work. Any solutions?

//Use @Mock instead of @Autowired

@Mock
private UsuarioMapper usuarioMapper; 

//In test method use the below
    Mockito.doReturn(info).when(usuarioMapper).XYXMethod(ArgumentMatchers.argThat(t24InfoMatcher));

Add config file that contains:

       @ComponentScan("The path to mapstract classes")

       @Configuration
       public class MapstructConfig {   
       }

And add to spring.factories file:

       org.springframework.boot.autoconfigure.EnableAutoConfiguration=
       "The path of the config class that created"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM