Java 我可以将bean自动连接到接口中吗?

Java 我可以将bean自动连接到接口中吗?,java,spring-boot,mapstruct,Java,Spring Boot,Mapstruct,我正在使用MapStruct,为此我必须定义一个具有相应映射函数的接口。可以通过使用默认的方法来实现一些逻辑,该方法使用@BeforeMapping和@AfterMapping注释。在这种带注释的默认方法中,我希望使用SpringBoot应用程序的配置类。我该怎么做?我可以将这样的配置(bean)自动连接到接口中吗?这样的代码应该是什么样子 从文档和您的提示中,我发现我可以使用@Context变量或抽象类,而不是使用接口 @Mapper public abstract class MyMapp

我正在使用
MapStruct
,为此我必须定义一个具有相应映射函数的接口。可以通过使用
默认的
方法来实现一些逻辑,该方法使用
@BeforeMapping
@AfterMapping注释。在这种带注释的默认方法中,我希望使用SpringBoot应用程序的配置类。我该怎么做?我可以将这样的配置(bean)自动连接到接口中吗?这样的代码应该是什么样子


从文档和您的提示中,我发现我可以使用@Context变量或抽象类,而不是使用接口

@Mapper
public abstract class MyMapper {

    private MyCustomService service;


    public abstract Target map(Source source);


    @AfterMapping
    protected after(Source source, @MappingTarget Target target) {
        // Use the service here
    }

    @Autowired
    public void setService(MyCustomService service) {
        this.service = service.
    }    
}
我当时两个都试过了。使用一个抽象类,它工作得很好,但使用@Context变量,默认方法不会被调用

以下是主要的映射方法:

@Mapping(target = "myTarget.partNumber", ignore = true)
public MyTarget mapSource2Target(final MySource mySource, final PartNumberMapConfiguration partNumberMapConfiguration);
以及后映射方法:

@Mapping(target = "myTarget.partNumber", ignore = true)
public MyTarget mapSource2Target(final MySource mySource, final PartNumberMapConfiguration partNumberMapConfiguration);
当我到达调用映射器的断点时,我无法进入映射方法。它只是一步一步地过去…而afterMapping方法的代码没有被执行

下面是我打算与@Context一起使用的类:

@组件(“零件号映射”)
@PropertySource(“类路径:abc.properties”)
@配置属性(前缀=“abc”)
公共类零件号配置{
私有映射partNumberMap=newhashmap();
公共映射getPartNumberMap(){
返回零件号映射;
}
公共无效设置零件号映射(最终映射零件号映射){
this.partNumberMap=partNumberMap;
}
}

不能将bean自动连接到接口中。但是,您可以使用MapStruct 1.2.0中的
@Context

例如:

@Mapper
public interface MyMapper {


    Target map(Source source, @Context MyCustomService service);

    @AfterMapper
    void after(Source source, @MappingTarget Target target, @Context MyCustomService service) {
        // Do what you need here
    }
}
另一种选择是使用抽象类而不是接口

@Mapper
public abstract class MyMapper {

    private MyCustomService service;


    public abstract Target map(Source source);


    @AfterMapping
    protected after(Source source, @MappingTarget Target target) {
        // Use the service here
    }

    @Autowired
    public void setService(MyCustomService service) {
        this.service = service.
    }    
}

您将服务分别用作自动连接或上下文。它也可以是一个配置类??上下文。什么都可以。您是在thr map方法中传递它的人。至于自动连线,它可以是任何Spring Bean公共抽象MyTarget MySourceMyTarget(最终发行,最终MyConfiguration MyConfiguration);(at)AfterMapping默认void AfterMapping(at)MappingTarget MyTarget,final Issue source,final(at)Context MyConfiguration MyConfiguration){…
AfterMapping方法不使用接口调用。使用抽象类它工作正常。这是配置文件:(at)组件(“PartNumberMap”)(at)属性源(“classpath:abc.properties”)(at)ConfigurationProperties(prefix=“abc”)public class PartNumberMapConfiguration{您能否更新您的问题,因为在注释中包含此内容一点也不清楚