How to inject guice dependency in mapstruct interface - java

时光怂恿深爱的人放手 提交于 2020-12-13 04:53:48

问题


My objects

 Public void Student(){
     private string name;
     private int age;
 }

Public void ClassRoom(){
   private string roomNo;
   private Student student; //Student Object
}

Public void School(){
   private string roomNo;
   private String student; //String student
}

I have an interface

@Mapper(componentModel = "jsr330", unmappedTargetPolicy = ReportingPolicy.IGNORE, builder = @Builder(disableBuilder = true))
public interface TestjkMapper {

    @Named("convertObjToString")
    static String convertObjToString(Student student) {
        return new Gson.tojson(student)
    }

   @Mapping(source = "student", target = "student",qualifiedByName = "convertObjToString")
   School mapClassRoomToSchool(@NonNull ClassRoom classRoom);

}

I am planning to inject that gson instead of new Gson()

As per this How can i combine Guice and Mapstruct?

I tried to make changes but not sure where to add that

@Inject
Gson gson

I tried like this

public interface TestjkMapper {

  @Inject
  Gson gson

    @Named("authorityToMap")
    static Map authorityToMap(Authority authority) {
        return gson.tojson(authority.tostring())
    }

}

I am getting compiler error as below

variable gson might not have been initialized

how to inject correctly inside that interface

Here also

bind(TestjkMapper.class).to(TestjkMapperImpl.class)

TestjkMapper - My interface

TestjkMapperImpl - This is generated at runtime. So not sure how to bind this

Exact question:

How to convert Student object to Student String using guice injected gson


回答1:


If you want to use custom injected components in your mappers you will need to use abstract classes instead of interfaces. You can't inject fields into interfaces.

In your example it will look like:

@Mapper(componentModel = "jsr330", unmappedTargetPolicy = ReportingPolicy.IGNORE, builder = @Builder(disableBuilder = true))
public abstract class TestjkMapper {

    @Inject
    Gson gson;

    @Named("convertObjToString")
    static String convertObjToString(Student student) {
        return gson.tojson(student)
    }

   @Mapping(source = "student", target = "student", qualifiedByName = "convertObjToString")
   School mapClassRoomToSchool(@NonNull ClassRoom classRoom);

}


来源:https://stackoverflow.com/questions/64770274/how-to-inject-guice-dependency-in-mapstruct-interface-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!