Error injecting object: returning null

1

When I inject an object into the class it returns null , it does not seem to be 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);
    }
}
    
asked by anonymous 02.10.2015 / 21:21

1 answer

1

The CDI is the Java EE 6 specification that takes care of the dependency injection part, and depends on a Web container for its default execution.

But you can use this powerful Java EE feature in a Java SE project as well. Here's how you can do this:

link

The most famous CDI implementation is Weld:

link

There are other projects that add more features to work with dependency injection, such as DeltaSpike, which can be useful depending on your needs.

I hope this can guide you.

    
09.10.2015 / 18:12