org.glassfi sh .hk2.api.UnsatisfiedDependencyException с использованием AbstractBinder с jersey 2 в карафе - PullRequest
0 голосов
/ 25 мая 2020

Мне нужно развернуть простое приложение для отдыха в карафе. Если я избегаю инъекции и возвращаю строку, это работает. Теперь я пытаюсь внедрить некоторую реализацию службы в остальной класс контроллера и получаю эту ошибку:

13:33:03.719 WARN [qtp129601981-217] /bioplatform/rest/upload-photo
javax.servlet.ServletException: javax.servlet.ServletException: A MultiException has 3 exceptions.  They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=BioplatformServiceImpl,parent=RestController,qualifiers={},position=0,optional=false,self=false,unqualified=null,1035680501)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of ru.mts.sales.bioplatfrom.rest.RestController errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on ru.mts.sales.bioplatfrom.rest.RestController
...
Caused by: org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=BioplatformServiceImpl,parent=RestController,qualifiers={},position=0,optional=false,self=false,unqualified=null,1035680501)

Я создал эту привязку на подсказках от Inte rnet, но, видимо, это не работает:

public class BundleModule extends AbstractBinder
{
  @Override
  protected void configure() {
    bind(BioplatformService.class).to(BioplatformServiceImpl.class).in(Singleton.class);
  }
}

Я регистрирую его в ResourceConfig:

class ApplicationConfig extends ResourceConfig {
  ApplicationConfig() {
    register(new BundleModule());
    register(RestApiActivator.class);
    register(MultiPartFeature.class);
    register(JacksonFeature.class);
    register(JacksonJsonProvider.class);
    packages(true, "ru.mts.sales.bioplatfrom.rest");
  }
}

Затем устанавливаю эту конфигурацию в активаторе OSGi;

public class RestApiActivator implements BundleActivator {
@Override
  public synchronized void start(BundleContext bundleContext) throws Exception {
    this.bc = bundleContext;
    this.tracker = new ServiceTracker(this.bc, HttpService.class.getName(), null) {

      @Override
      public Object addingService(ServiceReference serviceRef) {
        httpService = (HttpService) super.addingService(serviceRef);
        registerServlets();
        return httpService;
      }

      @Override
      public void removedService(ServiceReference ref, Object service) {
        if (httpService == service) {
          unregisterServlets();
          httpService = null;
        }
        super.removedService(ref, service);
      }
    };
    this.tracker.open();
  }
private void rawRegisterServlets() throws ServletException, NamespaceException, InterruptedException {

    ClassLoader myClassLoader = getClass().getClassLoader();
    ClassLoader originalContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
      Thread.currentThread().setContextClassLoader(myClassLoader);
      httpService.registerServlet(REST_ADDRESS, new ServletContainer(new ApplicationConfig()), getJerseyServletParams(), null); 
    } finally {
      Thread.currentThread().setContextClassLoader(originalContextClassLoader);
    }
  }

  private Dictionary<String, String> getJerseyServletParams() {
    Dictionary<String, String> jerseyServletParams = new Hashtable<>();
    jerseyServletParams.put("javax.ws.rs.Application", ApplicationConfig.class.getName());
    return jerseyServletParams;
  }
}

Это мой контроллер:

@Path("/rest")
public class RestController {
  private final BioplatformService bioService;
  @Inject
  public RestController(BioplatformService bioService) {
    this.bioService = bioService;
  }
  @POST
  @Path("/upload-photo")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public String uploadFileAndReturnList(File uis11) {
    return bioService.uploadPhoto(uis1);
  }
}

Сервис и его реализация:

public interface BioplatformService {
 String uploadPhoto(File imageStream);
}
@Singleton
public class BioplatformServiceImpl implements BioplatformService {
  private RestClient client;
  private ConfigProvider config;
  @Inject
  public BioplatformServiceImpl(RestClient client, ConfigProvider config) {
    this.client = client;
    this.config = config;
  }
@Override
  public String uploadPhoto(File image) {
...
}

Зависимости:

<dependency>
      <groupId>javax.ws.rs</groupId>
      <artifactId>javax.ws.rs-api</artifactId>
      <version>${javax.ws.rs.version}</version>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.core</artifactId>
      <version>${osgi.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.glassfish.jersey.containers</groupId>
      <artifactId>jersey-container-servlet-core</artifactId>
      <scope>provided</scope>
      <version>${org.glassfish.jersey.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.felix</groupId>
      <artifactId>org.apache.felix.http.bundle</artifactId>
      <version>2.2.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.felix</groupId>
      <artifactId>org.apache.felix.framework</artifactId>
      <scope>provided</scope>
      <version>4.6.0</version>
    </dependency>
    <dependency>
      <groupId>javax.activation</groupId>
      <artifactId>activation</artifactId>
      <version>1.1.1</version>
    </dependency>

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.12</version>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpmime</artifactId>
      <version>4.5.12</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <scope>provided</scope>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>org.glassfish.jersey.media</groupId>
      <artifactId>jersey-media-json-jackson</artifactId>
      <version>${org.glassfish.jersey.version}</version>
    </dependency>
...