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;
– Emir Marques
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'.
– fercosmig
You initiating the application by a
mainand wanting to recover an instance of a non-existent CDI context? Expect the instance ofUsuarioRepositorycome 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– Bruno César