Error when injecting object: returning null

Asked

Viewed 297 times

1

When I inject an object into the class it returns null, it seems that it is not instantiated.

Exception in thread "main" java.lang.NullPointerException
    at com.fercosmig.util.db.PopulaTabelaUsuario.main(PopulaTabelaUsuario.java:37)

PopulaTabelaUsuario:

public class PopulaTabelaUsuario {

    @Inject
    private static UsuarioRepository ur;

    public PopulaTabelaUsuario(){
    }

    public static void main(String[] args) {

        Usuario u1 = new Usuario();
        u1.setNome("Adamastor Teste");
        u1.setEmail("[email protected]");
        u1.setTipoUsuario(TipoUsuario.USER);
        u1.setUsername("ateste");
        u1.setPassword("ateste");
        ur.inserir(u1); // aqui dá erro.

    }

}

UsuarioRepository:

public class UsuarioRepository implements Serializable {

    private static final long serialVersionUID = 1L;

    private EntityManager em;

    @Inject
    public UsuarioRepository(EntityManager em) {
        this.em = em;
    }

    @Transactional
    public void inserir(Usuario usuario) {
        Criptografia c = new Criptografia();

        String senha = usuario.getPassword();
        usuario.setPassword(c.criptografiaSha256(senha));
        usuario.setDataCadastro(new Date());
        usuario.setAtivo(true);
        em.persist(usuario);
    }
}
  • For me it doesn’t make much sense to inject a static object. Try to change private Static Usuarioy repositorur, to private Usuariorepository ur;

  • I had put it this way, but Eclipse, in the error line, informs that it is wrong and suggests using Static to work: Cannot make a Static Reference to the non-static field ur: Change 'ur' to 'Static'.

  • You initiating the application by a main and wanting to recover an instance of a non-existent CDI context? Expect the instance of UsuarioRepository come from where? If you want to use CDI in a Java SE environment, see how this should be done. If you have a problem with this, please update the question I can help you with

1 answer

1

CDI is the Java EE 6 specification that takes care of the dependency injection part, and relies on a web container for its standard execution.

But you can use this powerful Java EE feature in a Java SE project as well. See this tutorial for how you can do this:

http://blog.rocketscience.io/dependency-injection-with-cdi-in-java-se/

The most famous CDI implementation is Weld:

http://weld.cdi-spec.org/

There are other projects that add even more resources to work with dependency injection, such as Deltaspike, which can be useful depending on your need.

I hope that can guide you now.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.