目前,我正在使用mapstruct来映射实体和do之间的数据,在映射器中,我需要使用@Autowired实例化一个类,在我需要实例化的类中,当我尝试执行以下操作时,我有一个将数据加载到缓存中的方法:@ Autowired存储库;IntelliJ告诉我:变量‘存储库’可能还没有初始化。如何正确地使用实例化类或使用所需的方法?
映射器
@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;
}
}
发布于 2021-09-09 16:19:39
根据这,如果使用Spring组件(即@Autowired RepositoryImpl repository
),则需要使用抽象类:
5.2。有时将Spring组件注入Mapper,我们需要在映射逻辑中使用其他Spring组件。在本例中,我们必须使用抽象类而不是接口:
@Mapper(componentModel = "spring") public abstract class
SimpleDestinationMapperUsingInjectedService
然后,我们可以使用一个著名的@Autowired注释很容易地注入所需的组件,并在代码中使用它:
@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); }
我们必须记住不要让注入的bean成为私有的!这是因为MapStruct必须访问生成的实现类中的对象。
https://stackoverflow.com/questions/69120868
复制相似问题