如何在 Spring Boot 的映射器接口中使用 @Autowired 正确实例化 class?

How to correctly instantiate a class using @Autowired in a mapper interface in Spring Boot?

我目前正在使用 mapstruct 在实体和 DTO 之间映射数据,在映射器中我需要使用 @Autowired 实例化 class,在 class 中我需要实例化我有一个方法将数据加载到缓存中,当我尝试执行以下操作时:@Autowired RepositoryImpl 存储库; IntelliJ 告诉我:变量 'repository' 可能还没有初始化。我怎样才能正确使用实例化 class 或使用我需要的方法?

映射器

@Service
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface DataMapper {

**@Autowired
RepositoryImpl repository;**

}

default DetailTemp mapDetail(String itemType, counter){

**ItemType itemType = repository.getType(itemType);**

DetailTemp detailTemp = new DetailTemp();
detailTemp.setPosition(counter);
detailTemp.setItemType(itemType);

return  DetailTemp;

}

}

根据 this,如果您使用 Spring 组件(即 @Autowired RepositoryImpl repository),则需要使用抽象 class:

5.2. Inject Spring Components into the Mapper Sometimes, we'll need to utilize other Spring components inside our mapping logic. In this case, we have to use an abstract class instead of an interface:

 @Mapper(componentModel = "spring") public abstract class
 SimpleDestinationMapperUsingInjectedService 

Then, we can easily inject the desired component using a well-known @Autowired annotation and use it in our code:

 @Mapper(componentModel = "spring") public abstract class
 SimpleDestinationMapperUsingInjectedService {
 
     @Autowired
    protected SimpleService simpleService;
 
     @Mapping(target = "name", expression = "java(simpleService.enrichName(source.getName()))")
     public abstract SimpleDestination sourceToDestination(SimpleSource source); } 

We must remember not to make the injected bean private! This is because MapStruct has to access the object in the generated implementation class.