6
respostas

Incompatibilidade com Injeção de Dependencia

Boa tarde!!

Gostaria de saber se há incompatibilidade para fazer injecao de dependencia nas classes de recurso anotadas com @Path?

Estou tentando fazer a injeção (@Inject) do meu repositório na classe de recurso e está dando problemas...

Alguem já teve problemas ao realizar @Inject nas classes de recursos?

6 respostas

Oi Andre! Qual o problema que está acontecendo?

Consegue colocar aqui o log da exception e o código de onde vc está tentando injetar e do que está sendo injetado?

Abraços!

Philippe,

Trata-se de um projeto de testes..

Segue

Classe que é injetada

package br.com.pedidovenda.repository;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceException;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.com.pedidovenda.model.Produto;
import br.com.pedidovenda.repository.filter.ProdutoFilter;
import br.com.pedidovenda.service.NegocioException;

public class ProdutoRepository implements Serializable{

    private static final long serialVersionUID = 1L;

    @Inject
    private EntityManager manager;

    public Produto guardar(Produto produto) {

        return manager.merge(produto);

    }

    public Produto porSku(String sku) {

        try{
            return manager.createQuery("from Produto where upper(sku) = :sku ", Produto.class)
                      .setParameter("sku", sku.toUpperCase())
                      .getSingleResult();    
        } catch (NoResultException e)
        {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public List<Produto> filtrados(ProdutoFilter filtro){

        Session session = manager.unwrap(Session.class);
        Criteria criteria = session.createCriteria(Produto.class);

        if (StringUtils.isNotBlank(filtro.getSku())){
            criteria.add(Restrictions.eq("sku", filtro.getSku()));
        }

        if (StringUtils.isNotBlank(filtro.getNome())){
            criteria.add(Restrictions.ilike("nome", filtro.getNome(), MatchMode.ANYWHERE));
        }

        return criteria.addOrder(Order.asc("nome")).list();
    }

    public Produto porId(Long id) {

        Produto produto = null;
        try{
            produto = manager.find(Produto.class, id);    
        } catch (Exception e){
            return null;
        }


        return produto;


    }

    public void excluir(Produto produtoExistente) {

        try{
            Produto produto = manager.find(Produto.class, produtoExistente.getId());
            manager.remove(produto);
            manager.flush();
        } catch (PersistenceException e){
            e.printStackTrace();
            throw new NegocioException("Produto não pode ser excluído.");
        }


    }

    public List<Produto> porNome(String nome) {
        return this.manager.createQuery("from Produto where upper(nome) like :nome", Produto.class)
                .setParameter("nome", nome.toUpperCase() + "%").getResultList();
    }

}

CLASSE QUE FAZ o @Inject

package br.com.pedidovenda.recursos;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.thoughtworks.xstream.XStream;

import br.com.pedidovenda.model.Produto;
import br.com.pedidovenda.repository.ProdutoRepository;

@Path("produto")
public class ProdutoResource {

    @Inject
    private ProdutoRepository produtos;

    @Path("{id}")
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Response buscar(@PathParam("id") Long id){

        Produto produto = produtos.porId(id);

        if (produto!=null){
            XStream xstream = new XStream();
            String xmlGerado = (String) produto.toXML();
            return Response.ok(xmlGerado, MediaType.APPLICATION_XML).build();
        }                
        else{
            return Response.status(404).entity("Produto não localizado.").build();
        }    

    }}

LOG DE EXCEPTION

HTTP Status 500 - A MultiException has 3 exceptions. They are:

type Exception report

message A MultiException has 3 exceptions. They are:

description The server encountered an internal error that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: A MultiException has 3 exceptions.  They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=ProdutoRepository,parent=ProdutoResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,26162089)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of br.com.pedidovenda.recursos.ProdutoResource errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on br.com.pedidovenda.recursos.ProdutoResource

    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:391)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:226)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
root cause

A MultiException has 3 exceptions.  They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=ProdutoRepository,parent=ProdutoResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,26162089)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of br.com.pedidovenda.recursos.ProdutoResource errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on br.com.pedidovenda.recursos.ProdutoResource

    org.jvnet.hk2.internal.Collector.throwIfErrors(Collector.java:88)
    org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:270)
    org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:414)
    org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
    org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:160)
    org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2445)
    org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:621)
    org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:606)
    org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:173)
    org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
    org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:94)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:63)
    org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:261)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:252)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1023)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:372)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:226)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
root cause

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=ProdutoRepository,parent=ProdutoResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,26162089)
    org.jvnet.hk2.internal.ThreeThirtyResolver.resolve(ThreeThirtyResolver.java:74)
    org.jvnet.hk2.internal.ClazzCreator.resolve(ClazzCreator.java:232)
    org.jvnet.hk2.internal.ClazzCreator.resolveAllDependencies(ClazzCreator.java:255)
    org.jvnet.hk2.internal.ClazzCreator.create(ClazzCreator.java:414)
    org.jvnet.hk2.internal.SystemDescriptor.create(SystemDescriptor.java:456)
    org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:160)
    org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2445)
    org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:621)
    org.jvnet.hk2.internal.ServiceLocatorImpl.getService(ServiceLocatorImpl.java:606)
    org.glassfish.jersey.internal.inject.Injections.getOrCreate(Injections.java:173)
    org.glassfish.jersey.server.model.MethodHandler$ClassBasedMethodHandler.getInstance(MethodHandler.java:185)
    org.glassfish.jersey.server.internal.routing.PushMethodHandlerRouter.apply(PushMethodHandlerRouter.java:74)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:112)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:115)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:94)
    org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:63)
    org.glassfish.jersey.process.internal.Stages.process(Stages.java:197)
    org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:261)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:252)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1023)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:372)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:226)
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186)
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
note The full stack trace of the root cause is available in the Apache Tomcat/9.0.0.M13 logs.

Apache Tomcat/9.0.0.M13

A exception está dizendo que ele não encontrou seu ProdutoRepository para ser injetado:

There was no object available for injection at Injectee(requiredType=ProdutoRepository,parent=ProdutoResource,qualifiers={}),position=-1,optional=false,self=false,unqualified=null,26162089)

Você está usando CDI em seu projeto?

Sim,

Estou usando CDI no projeto.

Coloca então um @RequestScoped em cima do ProdutoRepository pra ver se funciona

Então Philippe, tentei colocar, mas também não funcionou, dá o mesmo erro.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software